實現atoi()函數開始以前,測試了庫中的atoi()函數,發現庫中提供的atoi函數能夠處理許多異常,下面就是庫中能夠處理的異常:ide
1.指針爲NULL
函數
2.空字符串
測試
3.(+,-)號處理spa
4.遇到異常字符時的處理方式
3d
5.溢出時處理,分爲兩部分:指針
1).上溢出,輸出上界
blog
2).下溢出,輸出下界
字符串
那麼對這些異常進行處理就能夠完成一個簡單atoi()函數了。get
代碼實現:
it
/*My_Atoi.c*/ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <limits.h> typedef enum Ret { VALID, INVALID }Ret; Ret state = INVALID; //用來判斷異常的全局變量 int My_Atoi(const char* str) { int flag = 1; //正負 long long ret = 0; //返回值 assert(str); if(str == NULL) //空指針 { return (int)ret; } if(str == '\0') //空字符串 { return (int)ret; } while(*str == ' ') //空白字符 { str++; } if(str == '\0') //空白字符串 { return (int)ret; } else if(*str == '+' || *str == '-') { if(*str == '-') { flag = -1; } str++; } while(*str) { if((*str <= '9') && (*str >= '0')) { state = VALID; ret = ret * 10 + flag * (*str - '0'); str++; if(ret > INT_MAX) //上溢出 { state = INVALID; printf("上溢出,"); return (int)INT_MAX; } if(ret < INT_MIN) //下溢出 { state = INVALID; printf("下溢出,"); return (int)INT_MIN; } } else //異常字符 { return (int)ret; } } return (int)ret; } int main() { int ret = My_Atoi(""); //int ret = My_Atoi("1213"); //int ret = My_Atoi("-1213"); //int ret = My_Atoi("123aaa"); //int ret = My_Atoi("-111111111111111"); //int ret = My_Atoi("111111111111111"); if(state == INVALID) { printf("輸入非法!!\n"); } printf("ret = %d\n", ret); system("pause"); return 0; }
部分測試結果:
/*My_Atoi("")*/
/*My_Atoi("-1213")*/
/*My_Atoi("111111111111111")*/
/*My_Atoi("123aaa")*/
在之後寫一個庫中已有的函數,先使用它,並測試它能夠完成的事情,以及能夠處理的異常,只要考慮到那些異常處理,那麼這些函數就能夠很輕鬆搞定。