Understanding the atoi () function

I am a Python programmer to learn C from the book K & R. This will seem like a terribly trivial question, but nonetheless I'm at a dead end. The following is a snippet of code from the book K & R (RIP Ritchie!), 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 use any target other than counting the number of valid characters?
2) If (1) is true, the first cycle sets the value of "i" to the number of valid characters - how does the second cycle work without reselling I to 0?

Say, for example, I enter "2992" as an input to a function. I set the first for the loop to 3, so how does the rest of the function work? I can have all my problems, but any help would be really appreciated. Thanks, -Craig

+6
source share
6 answers
 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 idea of ​​ATOI.

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

2) And then inside the while loop, you look at each character and multiply by 10 and add the character by subtracting by 0.

And if you try with 2992. the number will be 2992.

+10
source

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

After that, i is the index of the first character without a space, which is exactly what you need to continue.

+4
source

No, the first loop skips spaces, as the comment says.

+1
source

The comment gives the answer: the first cycle is to skip spaces. For 2992 , i will remain 0 .

+1
source

The first for loop allows you to jump to the first character without spaces.

The condition between cycles marks the sign, if any.

Then the final for loop performs the actual conversion.

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

+1
source

1) no first for loop does not count the number of characters, but counts the first position of the number, if only the leading characters are spaces, i.e. for this "-2992" I will be 1, and for "2992" there will be 0, 2) sign = (s[i++] == '+') ? 1 : -1; sign = (s[i++] == '+') ? 1 : -1; this statement checks if the character i \ th th char is a character and increments the counter by 1 [i ++], and for the next for loop, I am the first starting digit in the string. if I do 0, then for the first conditional input your check-charter will be the place!

edit1: first entry is "space-2992"

0
source

Source: https://habr.com/ru/post/900453/


All Articles