Suppose if I have a character let's say char a ='9' and I need to convert it into interger value 9 .How can I do that?.I have tried using inbuilt function atoi().But it is giving error saying you can only pass constant pointer as a arugument.
1 Answer
It is simple. just subtract '0' from that character.
char a = '9'; int value = a - '0'; // value = 9. because ascii value of '9' is 57 and '0' is 48.
So actually it becomes
int value = 57 - 48;
That is value = 9.
1 Comment
Pete Becker
It’s not just because ASCII. The C and C++ language definitions require that the encodings for the characters
’0’ .. ‘9’ be contiguous and increasing. So ch - ‘0’ works for every character encoding.
'90'is not a validchar. See en.cppreference.com/w/cpp/language/character_literal.