字符串转换成整形值
字符串转换成整形值,能够考虑的异常因素有很多。编写代码之前设计测试用例很有帮助。
1 enum STATUS{STRNULL=0, STREMPTY, STRINVALID, STROVERFLOW, STRVALID}; 2 enum SIGN{NEGATIVE=0, POSITIVE}; 3 enum STATUS status = STRVALID; 4 enum SIGN sign = POSITIVE; 5 int str2int(const char *str) 6 { 7 long long num = 0; 8 9 if (str == NULL) 10 { 11 status = STRNULL; 12 13 return 0; 14 } 15 while (*str == ' ') 16 { 17 str++; 18 } 19 20 if (*str == '-' || *str == '+') 21 { 22 if (*str == '-') 23 { 24 sign = NEGATIVE; 25 } 26 if ( *(str+1) == '\0') 27 { 28 status = STREMPTY; 29 30 return 0; 31 } 32 33 str++; 34 } 35 else if (*str == '\0') 36 { 37 status = STREMPTY; 38 39 return 0; 40 } 41 else 42 { 43 while(*str != '\0') 44 { 45 if (*str >= '0' && *str <= '9') 46 { 47 num = num * 10 + *str - '0'; 48 49 if (num > 0x80000000) 50 { 51 status = STROVERFLOW; 52 53 return 0; 54 } 55 } 56 else 57 { 58 status = STRINVALID; 59 60 return 0; 61 } 62 63 str++; 64 } 65 66 } 67 68 if (sign == NEGATIVE) 69 { 70 num = -num; 71 } 72 73 return (int)num; 74 75 } 76 77 int main(int argc, char** argv) 78 { 79 char *pString = " -2147483648"; 80 81 int num = str2int(pString); 82 83 switch (status) 84 { 85 case STRVALID: 86 { 87 cout << num << endl; 88 } 89 break; 90 case STREMPTY: 91 { 92 cout << "Empty str" << endl; 93 } 94 break; 95 case STRNULL: 96 { 97 cout << "NULL str" << endl; 98 } 99 break; 100 case STROVERFLOW: 101 { 102 cout << "Overflow str" << endl; 103 } 104 break; 105 default: 106 { 107 cout << "NONE digit str" << endl; 108 } 109 } 110 111 system("pause"); 112 113 return 0; 114 }

浙公网安备 33010602011771号