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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.