how to convert char to int
hi there, i just want to know what function to use in converting a char into an int
like:
char temp;
cout << "enter something";
cin >> temp;
atoi(temp);
is this the right way?
jaepi
Practically a Master Poster
647 posts since Jul 2006
Reputation Points: 32
Solved Threads: 4
>>is this the right way?
No because atoi() takes a pointer to a null-terminated string and your variable temp is just a single character.
The quickest way is to simply subtract the ascii value of '0' from it like this: int n = temp - '0'; . Why does that work? Its because a char is a small integer and if you look at an ascii chart you will see that all characters have an ascii numerical value. Internally, programs know nothing at all about characters, only numeric values as shown in that ascii chart.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
thank you for that detailed explanation..
jaepi
Practically a Master Poster
647 posts since Jul 2006
Reputation Points: 32
Solved Threads: 4
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
> yes that is a correct way u can proceed.........
Over a year late, and still you missed the better answer from ~s.o.s~
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
It seems this zombi thread was started by incorrect and unclear question then proceeded with answers to another hypothetical questions and now start the next bla bla bla loop... ;)
That's my deposit in the discussion of char to int promotion...
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
> yes that is a correct way u can proceed.........
Over a year late, and still you missed the better answer from ~s.o.s~
Let's add another 3 years to that.
WaltP
Posting Sage w/ dash of thyme
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944