模仿c的字符转整数函数 atoi
1 #include<stdio.h> 2 enum Status {KValid = 0, KInvalid}; 3 int g_nStatus = KValid; 4 long StrToIntCore(char *str,bool minus) 5 { 6 long num = 0; 7 while (*str !='\0') 8 { 9 if (*str >'0' && *str<'9') 10 { 11 int flag = minus ? -1:1; 12 num = num * 10 + flag*(*str - '0'); 13 if ((!minus && num > 0x7FFFFFFF)||(minus && num <(signed int)0x80000000)) 14 { 15 num = 0; 16 break; 17 } 18 str++; 19 } 20 else 21 { 22 num = 0; 23 break; 24 } 25 } 26 if (*str == '\0') 27 { 28 g_nStatus = KValid; 29 } 30 return num; 31 } 32 int StrToInt(char *str) 33 { 34 g_nStatus = KInvalid; 35 long num = 0; 36 if (*str != NULL && *str !='\0') 37 { 38 bool minus = false; 39 if(*str == '+') 40 str++; 41 else if(*str == '-') 42 { 43 str++; 44 minus = true; 45 } 46 if (*str !='\0') 47 { 48 num = StrToIntCore(str,minus); 49 } 50 } 51 return int(num); 52 } 53 54 void main() 55 { 56 printf("%d",StrToInt("-12")); 57 }
在前面的代码中,把空字符串“”和只有一个正号或负号的情况都考虑到了。同事还考虑整数的最大值是0x7fffffff,最小值0x80000000,一次要分两种情况判断溢出。