By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,813 Members | 2,351 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,813 IT Pros & Developers. It's quick & easy.

how to convert character to integer c++ (urgent )

P: 11
hiii
i am taking input from a file as a character and have to convert it into integer to do some operations
eg the character input may be 1 , 0 , 2 etc.
and i need to convert them into integers ..
i have tried doing
unsigned char var_name;
int i;
i=int( var_name);

but it gives wrong output .. probably it is converting the character into ascii..
i cannot understand how to go about it ..
please help ...
Jun 19 '07 #1
Share this Question
Share on Google+
4 Replies


Meetee
Expert Mod 100+
P: 931
hiii
i am taking input from a file as a character and have to convert it into integer to do some operations
eg the character input may be 1 , 0 , 2 etc.
and i need to convert them into integers ..
i have tried doing
unsigned char var_name;
int i;
i=int( var_name);

but it gives wrong output .. probably it is converting the character into ascii..
i cannot understand how to go about it ..
please help ...

Use atoi function to convert char to int

Cheers!
Jun 19 '07 #2

P: 11
Use atoi function to convert char to int

Cheers!
hii
thankyou!!
it works ..
by the way .. why cant it convert unsigned char* to const char * ... imean it works when i declare the variable character .. but does not in case i declare the variable unsigned char .. :)
Jun 19 '07 #3

Meetee
Expert Mod 100+
P: 931
hii
thankyou!!
it works ..
by the way .. why cant it convert unsigned char* to const char * ... imean it works when i declare the variable character .. but does not in case i declare the variable unsigned char .. :)
For that try this:

unsigned char tmp = 'a';
int num = static_cast<int>(tmp);

For the sake of knowledge:
The static_cast operator converts expression to the type of type-id based solely on the types present in the expression. No run-time type check is made to ensure the safety of the conversion.( from http://msdn2.microsoft.com/en-us/library/ms861534.aspx)

Regards
Jun 19 '07 #4

weaknessforcats
Expert Mod 5K+
P: 9,197
You don't need atoi. That's a relic C function.

You convert a char to an int by assigning the char to the int.

Expand|Select|Wrap|Line Numbers
  1. char c = 'A';
  2. int x;
  3. x = c;    //x contains 65 which is the ASCII value of 'A'
  4. c = '2';
  5. x = c;    //x contains 62 which is the ASCII value of '2'
  6. x = c - 48;  //x contains 2  
  7.  
A char is just an 8-but integer so you can freely use as an integer.
Jun 19 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.