DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   how to convert char to int (http://www.daniweb.com/forums/thread78021.html)

jaepi May 11th, 2007 6:09 am
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?

Ancient Dragon May 11th, 2007 6:17 am
Re: how to convert char to int
 
>>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.

jaepi May 11th, 2007 6:21 am
Re: how to convert char to int
 
thank you for that detailed explanation..

~s.o.s~ May 11th, 2007 2:18 pm
Re: how to convert char to int
 
Why atoi is bad...

strtol is what you should be looking for.

rajenpandit Nov 25th, 2008 11:45 am
Re: how to convert char to int
 
Quote:

Originally Posted by jaepi (Post 364259)
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?

yes that is a correct way u can proceed.........
but the only thing u need to do is that u should use char array in place of char variable, and the function atoi is return an int value so u should store the result in some integer variable.
like
char temp[10]="10";
int i;
i=atoi(temp)*2;
cout<<i; \\ the output = 20;

Salem Nov 25th, 2008 1:41 pm
Re: how to convert char to int
 
> yes that is a correct way u can proceed.........
Over a year late, and still you missed the better answer from ~s.o.s~

ArkM Nov 25th, 2008 6:09 pm
Re: how to convert char to int
 
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...


All times are GMT -4. The time now is 11:12 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC