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?
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.
There are 3 ways to convert the char to int in C language as follows: Using Typecasting. Using sscanf() Using atoi()
We can convert a char array to double by using the std::atof() function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With