I wrote a function meant to act like the <stdlib.h> function atoi:
int _atoi(char *s)
{
int i, neg = 1, n = 0;
for (i = 0; s[i] != '\0'; i++)
{
if ((s[i] >= '0') && (s[i] <= '9'))
n = n * 10 + (s[i] - '0');
else if (s[i] == '-')
neg *= -1;
}
n *= neg;
return (n);
}
When I run it with something like
nb = _atoi(" + + - -98 Battery Street; San Francisco, CA 94111 - USA ");
printf("%d\n", nb);
The output is -9894111
But with a similar code like:
int _atoi(char *s)
{
int sign = 1, i = 0, res = 0;
while (!(s[i] <= '9' && s[i] >= '0') && s[i] != '\0')
{
if (s[i] == '-')
sign *= -1;
i++;
}
while (s[i] <= '9' && s[i] >= '0' && s[i] != '\0')
{
res = (res * 10) + (s[i] - '0');
i++;
}
res *= sign;
return (res);
}
The output is 98.
Which is what the real atoi function returns.
What's the difference between the two codes that would make the latter ignore everything after 8 (ie the - and the 94111)?
The loop condition of first code is
s[i] != '\0'. This means the loop will run until the end of string, regardless of wheather unconverted character exists before that.On the other hand, the loop condition of the last loop in the second code is
s[i] <= '9' && s[i] >= '0' && s[i] != '\0'. This will make the loop stop at the first character that is not a digit.Therefore, the first code will see
94111 -after non-digit characters following98while the second code won't.