+ 3
How can i convert char to int in C/C++ ?
I am trying to convert char to int in the following example but nothing works , please anyone char ch1 = '5' ,ch2='6'; int a=(int)ch1 + (int)ch2; cout<<a; // output should be 11 /* thanks in advance
10 Answers
+ 5
here's a little trick that'll get it done...
char x='12';
int y=x-'0';
Now y stores x's value as an integer...
+ 10
You can also do this:
char c1 = '5', c2 = '6' ;
int sum = (c1 - '0') + (c2 - '0') ;
But Anna's solution is way more easier to implement.
+ 5
By defining 5 and 6 as integers, not as chars '5' and '6'. Or you can remove the quotation marks: char a = 5, b = 6. Then a will be set to the char with the ASCII value 5 (whatever ASCII char that may be)
+ 5
thanks Tyrant that's what i was looking for
+ 3
Remove the quotation marks
+ 3
Anna thanks it worked
+ 1
(int)char will return the ASCII value of the char, not the number that the char represents. The ASCII value of '5'/'6' is 53/54, their sum is 107 and that's the value that is assigned to a.
+ 1
Anna But i want 11 as output..by adding 5 and 6. How can i get that?
+ 1
Anna that's okay, But my problem is that if those values are stored in a char datatype then what will be the approach?
+ 1
Nice! You're welcome đ