May 9, 2009 at 6:27pm May 9, 2009 at 6:27pm UTC
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 May 9, 2009 at 6:35pm UTC
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:59pm May 9, 2009 at 6:59pm UTC
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:05pm May 9, 2009 at 7:05pm UTC
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 May 9, 2009 at 7:31pm UTC
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 May 10, 2009 at 4:58am UTC
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().