C++實作atoi函數——考慮各類異常CASE
遇到一個實際問題,特别是邏輯并不複雜的情況,需要全方位考慮各種異常情況,隻有在事先考慮到各種情況,才能保證程式的健壯性。也就是說程式首先邏輯要正确,并且同等重要的是程式必須要有魯棒性。
列出輸入的可能情況,正常輸入是怎樣的,異常輸入是怎樣的,每種情況需要對應什麼輸出。需要多思考,對一個問題,需要全面列舉出它可能的bad input或者bad case,事先考慮好才不會給自己挖坑。
例如,考慮實作C++的int atoi(char * str)函數,将一個指定的字元數組轉換為一個整數
首先,我們考慮正常的情況,“123”->123,“1”->1;然後我們考慮異常情況,這塊直接關系你的程式時候的健壯
① str為NULL需要考慮,這種情況直接抛出異常
② 如果前面有空格的情況,需要去掉空格
③ 數字前面有正負号的情況,"+、-"需要特殊處理
④ 數字前有多個正負号,直接抛出異常
⑤ 如果字元包含非數字字元,需要截斷處理
⑥ 如果字元數組太長,轉換成int就會産生溢出,直接抛出異常
考慮到這些情況,程式就能hold住已知的全部異常輸入
#include <iostream>
using namespace std;
int myAtoi(char * str){
// 異常輸入①
if(str == NULL){
throw "param is NULL";
}
// 異常②
while(*str != '\0' && *str == ' '){
str ++;
}
// 異常③
bool isNeg = false;
if(*str == '+' || *str == '-'){
if(*str == '-'){
isNeg = true;
}
str ++;
}
// 異常④
if(*str < '0' || *str > '9'){
throw "not strat with number";
}
// 主體邏輯
int sum = 0;
while(*str != '\0'){
if(*str >= '0' && *str <= '9'){
sum = sum * 10 + *str - '0';
}else{
// 異常⑤
break;
}
// 異常⑥
if(sum < 0){
throw "over fill";
}
str ++;
}
if(isNeg){
sum = -1 * sum;
}
return sum;
}
int main() {
char str[100] = " -94032342";
int res = myAtoi(str);
cout <<res << endl ;
return 0;
}
結果如下
-94032342