i want a code to convert between the character datatype and the integer data type in c++ programming languge
How can i convert from charater to integer in c++ programming languge?
The other posters are correct that it's legal
to use a construction like:
int i = (int)c;
but the cast isn't necessary. The standard widening rules
of C and C++ automatically promote anything of type "char"
to type "int" within expression context. So it would
be equivalent to have said:
int i = c;
I suspect that the poster is really interested
in converting a character string representation of a
number into an integer. One poster suggested looking
up "itoa()", but I think they meant "atoi()":
char *p = "12345";
int i = atoi(p);
Another function worth looking at (which produces a "long"
rather than an "int") is:
strtol()
Reply:jainnys is right. You only have to cast it as an integer, because a single character is stored internally as an integer anyway. Just keep in mind that this gives you the ascii value...so don't go thinking that the character '3' will give you the number 3 when you convert it.
Reply:I don't remember the exact format but look up the "atoi()" function. That will do it.
Added: I looked it up... For arrays...
main()
{
char ary[5][]={"1","2","3","4","5"};
int v=0,k=0;
for(k=0; k%26lt;4; k++)
v+=atoi(ary[k]);
printf("%d",v"); // Will print '15'
}
Reply:Heres a sample for only ONE character
/* Convert.cpp */
/* Aim:- To change a character to an integer */
/* NOTE:- This program uses the old Borland C++ Compiler */
/* Some features may change */
/* By Senthil */
#include %26lt;iostream.h%26gt;
#include %26lt;conio.h%26gt;
void cnvrt_char(int);
void main()
{
char inp;
clrscr();
cout%26lt;%26lt;"Enter one character : ";
inp = getche();
cnvrt_char(inp);
getch();
}
void cnvrt_char(int inp)
{
cout%26lt;%26lt;"\nThe integer value for the character "%26lt;%26lt;(char)inp %26lt;%26lt;" is : "%26lt;%26lt;inp; //This is a continous line
//The variable inp was forced to show itself as a char
}
Instead of such a big program it could be solved like this:
Instaed of cnvrt_char(...) we can use cout%26lt;%26lt;(int)inp;
which meanas that we are forcing inp to show as an integer
It is called as Type Casting
Go ahead and try it for arrays
Reply:==================
char c;
c = 'c';
int a = (int) c;
==================
jainnys
Mind Experts Inc.
http://www.mindexp.com
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment