jonsb - 4 months ago 11

C++ Question

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?

Answer

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 less '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.