atoi 函数自实现

 1 #include <stdio.h>
 2 /*
 3 编码实现字符串转整型的函数(实现函数 atoi 的功能)。如将字符串“123”转化为 123,
 4 “-0123”转化为-123
 5 */
 6 int myatoi(const char *p)
 7 {
 8     int val = 0;
 9     int sign;
10     while(*p == ' '||*p == '\t')p++;
11     if(*p == '-'||*p == '+')
12     {
13         sign = (*p == '-'?-1:1);//必须用括号,= 和 ==  优先级不一样
14         p++;
15     }
16     
17     while(*p-'0'>=0&&*p-'9'<=0)
18     {
19         if(*p == '0')//考虑符号 后第一个字符为'0'的情况-0123  没有这样的数字吧,直接归0
20             return 0;
21         else
22             val = val*10+(*p-'0');    
23         p++;
24     }
25     return sign*val;
26     
27 }
28 int main(void)
29 {
30     char *p = "        -123a44sdfdf";
31     int val = myatoi(p);
32     printf("val = %d\n",val);
33     
34     return 0;
35 }

猜你喜欢

转载自www.cnblogs.com/wangchaomahan/p/10049811.html