atoi实现

来源:互联网 发布:js获取style属性 编辑:程序博客网 时间:2024/06/05 02:32

http://blog.csdn.net/richerg85/article/details/18729235

atoi实现

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. int atoi(char *str)  
  2. {  
  3.         if(!str)  
  4.                 return -1;  
  5.         bool bMinus=false;  
  6.         int result=0;  
  7.   
  8.         if(('0'>*str || *str>'9')&&(*str=='+'||*str=='-'))  
  9.         {  
  10.                if(*str=='-')  
  11.                 bMinus=true;  
  12.                *str++;  
  13.         }  
  14.         while( *str != '\0')  
  15.         {  
  16.                 if('0'> *str || *str>'9')  
  17.                         break;  
  18.                 else  
  19.                         result = result*10+(*str++ - '0');  
  20.         }  
  21.   
  22.         if (*str != '\0')//no-normal end  
  23.                 return -2;  
  24.   
  25.         return bMinus?-result:result;  
  26. }  

重写的atoi函数,没有考虑溢出的情况。

 if(('0'>*str || *str>'9')&&(*str=='+'||*str=='-'))//判读第一个字符是否为数字的正负号

if (*str != '\0')//no-normal end,当上文的while循环不正常退出,应视为字符串不合法,例如“+1234abc”

测试:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. char *c1 = "12345";  
  2.         char *c2 = "-12345";  
  3.         char *c3 = "bat-123";  
  4.         char *c4 = "+123abc";  
  5.   
  6.   
  7.         printf("c1=%d\n",atoi(c1));  
  8.         printf("c2=%d\n",atoi(c2));  
  9.         printf("c3=%d\n",atoi(c3));  
  10.         printf("c4=%d\n",atoi(c4));  

输出结果为:

c1=12345
c2=-12345
c3=-2
c4=-2

0 0
原创粉丝点击