http://blog.csdn.net/richerg85/article/details/18729235
atoi实现
[cpp] view plain copy int atoi(char *str) { if(!str) return -1; bool bMinus=false; int result=0; if(('0'>*str || *str>'9')&&(*str=='+'||*str=='-')) { if(*str=='-') bMinus=true; *str++; } while( *str != '\0') { if('0'> *str || *str>'9') break; else result = result*10+(*str++ - '0'); } if (*str != '\0')//no-normal end return -2; return bMinus?-result:result; } 重写的atoi函数,没有考虑溢出的情况。
if(('0'>*str || *str>'9')&&(*str=='+'||*str=='-'))//判读第一个字符是否为数字的正负号
if (*str != '\0')//no-normal end,当上文的while循环不正常退出,应视为字符串不合法,例如“+1234abc”
测试:
[cpp] view plain copy char *c1 = "12345"; char *c2 = "-12345"; char *c3 = "bat-123"; char *c4 = "+123abc"; printf("c1=%d\n",atoi(c1)); printf("c2=%d\n",atoi(c2)); printf("c3=%d\n",atoi(c3)); printf("c4=%d\n",atoi(c4)); 输出结果为:
c1=12345 c2=-12345 c3=-2 c4=-2