+ 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

23rd Oct 2018, 6:35 PM
Anubhav Singh
Anubhav Singh - avatar
10 Réponses
+ 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...
23rd Oct 2018, 7:32 PM
Mensch
Mensch - avatar
+ 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.
23rd Oct 2018, 7:13 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 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)
23rd Oct 2018, 6:49 PM
Anna
Anna - avatar
+ 5
thanks Tyrant that's what i was looking for
23rd Oct 2018, 7:34 PM
Anubhav Singh
Anubhav Singh - avatar
+ 3
Remove the quotation marks
23rd Oct 2018, 6:52 PM
Anna
Anna - avatar
+ 3
Anna thanks it worked
23rd Oct 2018, 6:53 PM
Anubhav Singh
Anubhav Singh - avatar
+ 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.
23rd Oct 2018, 6:46 PM
Anna
Anna - avatar
+ 1
Anna But i want 11 as output..by adding 5 and 6. How can i get that?
23rd Oct 2018, 6:48 PM
Anubhav Singh
Anubhav Singh - avatar
+ 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?
23rd Oct 2018, 6:52 PM
Anubhav Singh
Anubhav Singh - avatar
+ 1
Nice! You're welcome 😃
23rd Oct 2018, 6:54 PM
Anna
Anna - avatar