Reputation: 410
I want to convert char
to int
in c++, I used char a1
and to convert (int)a1
but I got wrong values, for example:
if a1 is '1'
then 49
if a1 is '2'
then 50
etc...
Why is this? How can I resolve this?
Upvotes: 1
Views: 12231
Reputation: 963
To get real value subtract the initial value like
char x='1'; //ascii value=49
int xx=x-'0' //49-48==1
char a='C'; //67
char aa=a-'A' //67-65=2 means third char of Alphabet
or you can type cast to get exact value
Hope you get the idea.
Upvotes: 1
Reputation: 126
int atoi (const char * str)
this function can be helpful in this regard. See the documentation here atoi() c++ reference
Upvotes: 3
Reputation: 78
It's because (int)a
converts just type but not the value. Literally, it says to compiler 'treat value of a
as an int
value' which in case of '1' returns its ASCII code 49.
To translate the actual value you can use:
// num == 49 - 48;
int num = (int)a - (int)'0';
Upvotes: 1
Reputation: 1125
This happens because char
values are usually encoded in ASCII. This means that '1'
, for example, is represented by the numerical value 49. To have an alphabetical conversion (i.e. convert '1'
to 1
), take a look at std::to_string, or, if you're working with c-style strings, at itoa.
Upvotes: 0