Advertisement

Casting

Started by March 21, 2003 09:48 PM
3 comments, last by Zorbfish 21 years, 7 months ago
This is really odd... Im casting a char to an int which is easy. The problem is that Im not recieving the correct value. string temp="#1"; int i = (int)temp[1]; cout << i; output: 49 ??? What the? Shouldn''t it cast it to just plain 1? What am I doing wrong here? I feel like such a n00b.
Nope, the character value for the digit does not equal the numerical value of the digit.. they start at 49 and go up..
Disclaimer: "I am in no way qualified to present advice on any topic concerning anything and can not be held responsible for any damages that my advice may incurr (due to neither my negligence nor yours)"
Advertisement
temp[1] is the ASCII character ''1'' not the number 1. The value of that character is 49. If you are working with single chars and want to change those single chars to their equivolent number you can subtract ''0'' from them.

int i = temp[1] - ''0'';

cout << i;

output:

1


Qui fut tout, et qui ne fut rien
Invader''s Realm
That''s the correct output: 49 is the ascii code for the character 1

Don''t believe then look it up on an ASCII chart.

btw ''0'' is ascii code 48
well I knew it was an ascii code just wasn't sure why it casted to that so my solution is:

int i = (int)temp[1] - '0';

thanks

EDIT

you guys beat me to it

[edited by - Zorbfish on March 21, 2003 10:55:54 PM]

[edited by - Zorbfish on March 21, 2003 10:56:35 PM]

This topic is closed to new replies.

Advertisement