atoi程序
来源:互联网 发布:淘宝店铺会员卡删除 编辑:程序博客网 时间:2024/06/14 04:30
最主要的是要考虑输入条件,程序写出来了远不是面试官的目的。各种异常情况的处理、边界条件的处理,才是面试官主要考察的内容。
我所能想到的测试用例有:
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;
- }
#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)会比较稳定。
- atoi程序
- 写个atoi程序
- 自己写一个atoi程序
- atoi
- atoi
- atoi
- atoi()
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- atoi
- Java中的泛型
- 行车记录仪效果由=方案(主控芯片)+镜头+图像传感器
- 编程之找寻最大的K个数
- tslib-master移植
- 语法错误 : 缺少“;”(在“类型”的前面)的解决方案
- atoi程序
- STM32之SysTick嘀嗒定时器
- Linux常用解压缩命令
- Struts2 基本数据类型转换的例子 详解析
- 基于mini2440的USB视频采集
- JS基础
- 一步步用python制作游戏外挂
- 求和为某正整数的所有正整数集合
- JS window.open