Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a single char into an int [duplicate]

Tags:

c++

char

I have a string of digits, e.g. "123456789", and I need to extract each one of them to use them in a calculation. I can of course access each char by index, but how do I convert it into an int?

I've looked into atoi(), but it takes a string as argument. Hence I must convert each char into a string and then call atoi on it. Is there a better way?

like image 726
jonsb Avatar asked Jan 13 '09 16:01

jonsb


People also ask

Can I convert a char to an int?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

How do I convert a char to an int in c?

There are 3 ways to convert the char to int in C language as follows: Using Typecasting. Using sscanf() Using atoi()

How do I convert a char to a double in C++?

We can convert a char array to double by using the std::atof() function.


1 Answers

You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).

Therefore the integer value for any digit is the digit minus '0' (or 48).

char c = '1'; int i = c - '0'; // i is now equal to 1, not '1' 

is synonymous to

char c = '1'; int i = c - 48; // i is now equal to 1, not '1' 

However I find the first c - '0' far more readable.

like image 94
Binary Worrier Avatar answered Sep 20 '22 11:09

Binary Worrier