字符串转换成整形值,能够考虑的异常因素有很多。编写代码之前设计测试用例很有帮助。
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) == '