-->

Understanding an atoi() function

2020-06-17 05:55发布

问题:

I'm a python programmer getting to learn C from the K&R book. This will seem like an awfully trivial question, but I'm stumped nonetheless. Attached below is a snippet of code from the K&R (RIP Ritchie!) book which implements the atoi() function.

atoi(s) /*convert s to integer */
char s[];
{
    int i, n, sign;
    for (i=0; s[i]==' '||s[i] == '\n' || s[i] == '\t'; i++)
    ;   /* skip whitespace */
    sign = 1;
    if (s[i] == '+' || s[i] = '-')  /* sign */
        sign = (s[i++] == '+') ? 1 : -1;
    for (n=0; s[i] >= '0' && s[i] <= '9'; i++)
        n = 10 * n + s[i] - '0';
    return (sign * n);
}

My questions:

1) Does the first 'for' loop serve any purpose besides counting the number of valid characaters?
2) If (1) is true, the first loop sets the value of 'i' to the number of valid characters - how does the second for loop work without reseting i to 0?

Say for example I enter '2992' as an input to the function. The first for loop sets i to 3, so how does the rest of the function work? I may have my basics all messed up but any help would be really appreciated. Thanks, -Craig

回答1:

int atoi(char* str)
{
    if(!str)
        printf("Enter valid string");

    int number = 0;
    char* p = str;

    while((*p >= '0') && (*p <= '9'))
    {
        number = number * 10 + (*p - '0');
        p++;
    } 
    return number;
}

Here is the whole idea behind ATOI.

1) You set the pointer at the start of the char array

2) And then inside while loop you go over each character and multiply by 10 and add the character by subtracting by 0.

And if you will try with 2992. the number would be 2992 as well.



回答2:

The first loop does what the comment says: it skips whitespace.

After it, i is the index of the first non-whitespace character, which is exactly what you need to proceed.



回答3:

No, the first loop skips whitespace, like the comment says.



回答4:

The comment provides the answer: the first loop is to skip whitespace. For 2992, i will remain 0.



回答5:

The first for loop advances i to point to the first non-whitespace character.

The conditional between the loops makes note of the sign, if any.

Then the final for loop does the actual conversion.

Finally, the sign is applied, and the result is returned.



回答6:

1) no first for loop does not count the number of character but it counts the first position of number if only starting chars are whitespaces i.e for this " -2992" i will be 1 and for "2992" i will be 0. 2) sign = (s[i++] == '+') ? 1 : -1; this statement checks if the i\'th char is a sign and makes the counter raise by 1[i++] and for the next for loop this i is the first starting digit in the string. if i makes 0 then for first conditional input your checking charter will be space!

edit1: first input is "space space-2992"



标签: c atoi