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
1 2 3 4 5 6 7
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??
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.