1

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
    `'90'` is not a valid `char`. See https://en.cppreference.com/w/cpp/language/character_literal. – R Sahu Apr 11 '19 at 02:36

1 Answers1

4

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.

Faruk Hossain
  • 1,205
  • 5
  • 12
  • 2
    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. – Pete Becker Apr 11 '19 at 04:08