atoi程序

来源:互联网 发布:淘宝店铺会员卡删除 编辑:程序博客网 时间:2024/06/14 04:30

最主要的是要考虑输入条件,程序写出来了远不是面试官的目的。各种异常情况的处理、边界条件的处理,才是面试官主要考察的内容。

我所能想到的测试用例有:

1,字符串内含有非法字符,非法字符的定义为0-9,- 之外的所有字符

2,字符串表示负数

3,字符串表示的整数溢出


以下是我写的myatoi和UT

[cpp] view plaincopyprint?
  1. #include <string.h>   
  2. int myatoi(const char* a);  
  3.   
  4. void TestString(const char* str)  
  5. {  
  6.     printf("%s = %d\r\n", str, myatoi(str));      
  7. }  
  8. void Test()  
  9. {  
  10.     const char* test[] = {"0""0x1","-","01""-1","1","123","1000000000","-1000000000","100000000000","-100000000000"};  
  11.     for(int i = 0; i < sizeof(test) / sizeof(const char*); i++)  
  12.     {  
  13.         TestString(test[i]);  
  14.     }  
  15. }  
  16.   
  17. int myatoi(const char* a)  
  18. {  
  19.     if(a == NULL || strlen(a) == 0)  
  20.     {  
  21.         printf("empty string!\r\n");  
  22.         return 0;  
  23.     }  
  24.   
  25.     int t = a[0];  
  26.     int i = 0;  
  27.     if(t > '9' || t < '0')  
  28.     {  
  29.         if(t != '-')  
  30.         {  
  31.             printf("illegal char!\r\n");  
  32.             return 0;  
  33.         }  
  34.         else if(strlen(a) < 2)  
  35.         {  
  36.             printf("illegal char!\r\n");  
  37.             return 0;  
  38.         }  
  39.         else  
  40.         {  
  41.             i = 1;  
  42.         }  
  43.     }  
  44.   
  45.     for(; i < strlen(a); i++)  
  46.     {  
  47.         if((a[i] > '9' || a[i] < '0'))  
  48.         {  
  49.             printf("illegal char!\r\n");  
  50.             return 0;  
  51.         }  
  52.     }  
  53.     int sign = 1;  
  54.     int pos = 0;  
  55.     if(a[0] == '-')  
  56.     {  
  57.         sign = -1;  
  58.         pos++;  
  59.     }  
  60.     int n = 0;  
  61.     while(pos < strlen(a))  
  62.     {  
  63.         if(n * 10 / 10 != n)  
  64.         {  
  65.             printf("overflow!\r\n");  
  66.             return 0;  
  67.         }  
  68.         n = n * 10 + (a[pos++] - '0');  
  69.     }  
  70.     return n * sign;  
  71. }  

写完了以后总觉得不爽,看了看cplusplus上对atoi函数的定义,感觉这个C函数的声明本身就有问题。异常条件下返回0,这种异常处理方式很容易导致客户程序员犯下很难debug到的错误。感觉如果定义为 bool atoi(const char* a, int& i)会比较稳定。
原创粉丝点击