atoi函数

#include <stdio.h>
#include <ctype.h>

#if 0
/* atoi: convert s to integer */
int atoi(char s[])
{
        int i, n;

        n = 0;
        for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
                n = 10 * n + (s[i] - '0');

        return n;
}
#endif

/* atoi: convert s to integer; version 2 */
int atoi(char s[])
{
        int i, n, sign;

        for (i = 0; isspace(s[i]); i++) /* skip white space */
                ;
        sign = (s[i] == '-') ? -1 : 1;
        if (s[i] == '+' || s[i] == '-') /* skip sign */
                i++;
        for (n = 0; isdigit(s[i]); i++)
                n = 10 * n + (s[i] - '0');

        return sign * n;
}

int main(void)
{
        printf("%d\n", atoi("19"));
        return 0;
}

你可能感兴趣的:(atoi函数)