经常有面试官让写atoi()函数,初看还挺吓人的,标准库函数啊。下面给个例子以备不测。
1: int my_atoi(const char *str)
2: {
3: long int result = 0;
4: char sign = '+';
5:
6: while (*str == ' ')
7: {
8: str++;
9: }
10:
11: if (*str == '-'||*str == '+')
12: {
13: sign = *str++;
14: }
15:
16: while (isdigit(*str))
17: {
18: result = result * 10 + (*str++ - '0');
19: }
20: return sign == '+' ? result: -result;
21: }
为了节省空间,其实str++没必要写那么紧凑的。至于用不用isdigit都想,ASCII表也不会有变化了,用>,<判断范围也是可以的。