### string to int. please explain this given solution

hello programmers,

I had to write a code that extracts digits from a string array and converts them to type int.
the below is given solution of where the digit strings are converted.
the 'commands' is a string array
 ``1234567`` `````` while( index < commands.length() && isdigit( commands[ index ] ) ) { int digit = commands[ index ] - '0'; quantity = quantity * 10 + digit; if (quantity > 1000) break; index = index + 1; } ``````

i'm confused with the line2 `int digit = commands[ index ] - '0';`
why would i need to subtract '0' from the digit element??
The integer representation is its ASCII code.
http://www.ascii-code.com/

For example, the ASCII code for '3' is 51 and the ASCII code for '0' is 48. 51 - 48 = 3, which is the integral representation of '3'.
C++ requires that for the characters representing decimal digits '0' '1' '2' ... '9' , the value of each character following '0' should be one greater than the the value of the previous character.

For example, in the character encoding in use, if the integer value of character '0' is 72, then the value of '1' would be 73, the value of '2' would be 74 etc.

Therefore '7' - '0' would yield the integer 7.
Using the same encoding as in the example above, '7' - '0' == 79 - 72 == 7

> The integer representation is its ASCII code

Not necessarily. The specific values of the members of the character set in use are locale specific.
Last edited on
this so much makes sense!!! thank you all~~
Topic archived. No new replies allowed.