简体   繁体   中英

C++ Convert Ascii Int To Char To Int

Im able to convert most things without a problem, a google search if needed. I cannot figure this one out, though.

I have a char array like:

char map[40] = {0,0,0,0,0,1,1,0,0,0,1,0,1... etc

I am trying to convert the char to the correct integer, but no matter what I try, I get the ascii value: 48/ 49.

I've tried quite a few different combinations of conversions and casts, but I cannot end up with a 0 or a 1, even as a char.

Can anyone help me out with this? Thanks.

The ascii range of the characters representing integers is 48 to 57 (for '0' to '9'). You should subtract the base value 48 from the character to get its integer value.

char map[40] = {'0','0','0','0','0','1','1','0','0','0','1','0','1'...};
int integerMap[40];

for ( int i = 0 ;i < 40; i++)
{
   integerMap[i] = map[i] - 48 ;
   // OR
   //integerMap[i] = map[i] - '0';


}

If the char is a literal, eg '0' (note the quotes), to convert to an int you'd have to do:

int i = map[0] - '0';

And of course a similar operation across your map array. It would also be prudent to error-check so you know the resulting int is in the range 0-9.

The reason you're getting 48/49 is because, as you noted, direct conversion of a literal like int i = (int)map[0]; gives the ASCII value of the char.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM