0

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?

8
Contributors
8
Replies
25
Views
10 Years
Discussion Span
Last Post by WaltP
1

>>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.

-1

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;
Votes + Comments
Unbelievable..
0

> yes that is a correct way u can proceed.........
Over a year late, and still you missed the better answer from ~s.o.s~

0

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...

-1

Or you can download this header and include it, and to use the functions, do this:

int i;
string s;
cin>>s;
i=c2a<int>(s)

Edited by Mahkoe: n/a

Votes + Comments
bump 4 year old thread
0

> 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.

Edited by WaltP: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.