Search code examples
c++atoi

atoi implementation in C++


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. )


Solution

  • Each step that line does two things:

    1. Shifts all digit left by a place in decimal
    2. Places the current digit at the ones place

    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:

    1. i = 0str[i] = '8': res = 0 * 10 + 8 = 8
    2. i = 1str[i] = '9': res = 8 * 10 + 9 = 89
    3. i = 2str[i] = '7': res = 89 * 10 + 7 = 897
    4. i = 3str[i] = '8': res = 897 * 10 + 8 = 8978
    5. i = 4str[i] = '9': res = 8978 * 10 + 9 = 89789

    And there's your result.