最主要的是要考慮輸入條件,程式寫出來了遠不是面試官的目的。各種異常情況的處理、邊界條件的處理,才是面試官主要考察的內容。
我所能想到的測試案例有:
1,字串內含有非法字元,非法字元的定義為0-9,- 之外的所有字元
2,字串表示負數
3,字串表示的整數溢出
以下是我寫的myatoi和UT
#include <string.h>int myatoi(const char* a);void TestString(const char* str){printf("%s = %d\r\n", str, myatoi(str)); }void Test(){const char* test[] = {"0", "0x1","-","01", "-1","1","123","1000000000","-1000000000","100000000000","-100000000000"};for(int i = 0; i < sizeof(test) / sizeof(const char*); i++){TestString(test[i]);}}int myatoi(const char* a){if(a == NULL || strlen(a) == 0){printf("empty string!\r\n");return 0;}int t = a[0];int i = 0;if(t > '9' || t < '0'){if(t != '-'){printf("illegal char!\r\n");return 0;}else if(strlen(a) < 2){printf("illegal char!\r\n");return 0;}else{i = 1;}}for(; i < strlen(a); i++){if((a[i] > '9' || a[i] < '0')){printf("illegal char!\r\n");return 0;}}int sign = 1;int pos = 0;if(a[0] == '-'){sign = -1;pos++;}int n = 0;while(pos < strlen(a)){if(n * 10 / 10 != n){printf("overflow!\r\n");return 0;}n = n * 10 + (a[pos++] - '0');}return n * sign;}
寫完了以後總覺得不爽,看了看cplusplus上對atoi函數的定義,感覺這個C函數的聲明本身就有問題。異常條件下返回0,這種異常處理方式很容易導致客戶程式員犯下很難debug到的錯誤。感覺如果定義為 bool atoi(const char* a, int& i)會比較穩定。