Given this implementation of atoi in C++
// A simple atoi() function
int myAtoi(char *str)
{
int res = 0; // Initialize result
// Iterate through all characters of input string and update result
for (int i = 0; str[i] != '\0'; ++i)
res = res*10 + str[i] - '0';
// return result.
return res;
}
// Driver program to test above function
int main()
{
char str[] = "89789";
int val = myAtoi(str);
printf ("%d ", val);
return 0;
}
How exactly does the line
res = res*10 + str[i] - '0';
Change a string of digits into int values? (I'm fairly rusty with C++ to be honest. )
Each step that line does two things:
The part str[i] - '0'
takes the ASCII character of the corresponding digit which are sequentially "0123456789" and subtracts the code for '0' from the current character. This leaves a number in the range 0..9 as to which digit is in that place in the string.
So when looking at your example case the following would happen:
i = 0
→ str[i] = '8'
: res = 0 * 10 + 8 = 8
i = 1
→ str[i] = '9'
: res = 8 * 10 + 9 = 89
i = 2
→ str[i] = '7'
: res = 89 * 10 + 7 = 897
i = 3
→ str[i] = '8'
: res = 897 * 10 + 8 = 8978
i = 4
→ str[i] = '9'
: res = 8978 * 10 + 9 = 89789
And there's your result.