Converting a single char to integer

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
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';

you can use atoi().
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
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.
The second method I provided will do just that. It will provide the numeric value, not the ASCII character value.
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?
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.