Converting a single char to integer

May 9, 2009 at 6:27pm
Hi all,

I have this problem, if let say I have an array of char says txt[10].

How do I convert like txt[0] to an integer?and not as a whole string
May 9, 2009 at 6:35pm
It depends on what you are really asking.

txt[0] by itself is an integer.

int i = txt[0];

On the other hand, if you want the value of the character '7', then this is the easiest:

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

May 9, 2009 at 6:48pm
you can use atoi().
May 9, 2009 at 6:59pm
Hi panGalactic,

Lets say I declare

char txt[10];
txt[0] ='1';

How can I convert txt[0] to an integer value which return as 1 and not 49?

Atoi can only convert string not a single char
May 9, 2009 at 7:04pm
txt[0] ='1';

this is wrong.. this means you putting 49 inside and not 1.
that means you want to convert 49 to 1.. correct..

what panGalactic said is perfect then.
1
2
int i = txt[0] - '0';  //49 - 48 = 1


this will give 1.
May 9, 2009 at 7:05pm
The second method I provided will do just that. It will provide the numeric value, not the ASCII character value.
May 9, 2009 at 7:31pm
Thanks guys it works but then my main proj is, I have to read an input file which consist of chars, like

1
1234

Then using ifstream I store them as char in the char array. I need to use individual numbers there to perform calculation, but when they are in the array I cannt convert it to interger one by one. Any solutions to that?
May 10, 2009 at 4:58am
so you have array which is storing the numbers... if i am correct..

first array has 1 and second has 1234.
you want output as numeric 1 and numeric 1234...

then why cant you use atoi().
Topic archived. No new replies allowed.