atoi代码实现
来源:互联网 发布:sas数据分析大赛 编辑:程序博客网 时间:2024/06/05 00:54
atoi函数
atoi函数是实现数字字符串转整型数,实现代码的时候,要特别注意以下几点:
- 前面有空格,调过
- 要注意符号,即是正还是负数
- 非法输入
- 处理溢出
代码实现
int my_atoi(const char *str){ const char *s; char c; unsigned int cutoff; int acc; int neg, any, cutlim; if(str == NULL) { errno = EINVAL; return false; } s = str; do{ c = *s++; }while(c == ' ' || c == '\t'); if(c == '-'){ neg = 1; c = *s++; } else { neg = 0; if(c == '+') c = *s++; } cutoff = neg? INT_MIN : INT_MAX; cutlim = cutoff % 10; cutoff /= 10; acc = any = 0; while(c >= '0' && c <= '9') { c -= '0'; if(acc > cutoff || (acc == cutoff && c > cutlim)) { any = -1; break; } else { any = 1; acc *= 10; acc += c; } c = *s++; } if(any < 0) { errno = ERANGE; acc = neg? INT_MIN : INT_MAX; return acc; } else if(any == 0) { errno = EINVAL; } else if(neg) { acc = -acc; } return acc;}
测试代码
void Test(const char *str){ errno = -1; int result = my_atoi(str); if(errno == EINVAL) printf("str %s is : EINVAL \n",str); else if(errno == ERANGE) printf("str %s is : ERANGE %d \n",str, result); else printf("str %s is : %d \n",str,result);}int main(int argc, char const *argv[]){ Test(""); Test("123"); Test("+123"); Test("-123"); Test("1a33"); Test("+0"); Test("-0"); //有效的最大正整数, 0x7FFFFFFF Test("+2147483647"); Test("-2147483647"); Test("+2147483648"); //有效的最小负整数, 0x80000000 Test("-2147483648"); Test("+2147483649"); Test("-2147483649"); Test("+"); Test("-"); Test("10522545459"); Test("-10522545459"); Test(" +4488"); Test(" - 321"); return 0;}
结果输出如下:
str is : EINVAL str 123 is : 123 str +123 is : 123 str -123 is : -123 str 1a33 is : 1 str +0 is : 0 str -0 is : 0 str +2147483647 is : 2147483647 str -2147483647 is : -2147483647 str +2147483648 is : ERANGE 2147483647 str -2147483648 is : -2147483648 str +2147483649 is : ERANGE 2147483647 str -2147483649 is : ERANGE -2147483648 str + is : EINVAL str - is : EINVAL str 10522545459 is : ERANGE 2147483647 str -10522545459 is : ERANGE -2147483648 str +4488 is : 4488 str - 321 is : EINVAL
参考资料
atoi函数的实现
http://arieshout.me/2012/03/implementation-of-atoi.html
0 0
- atoi代码实现
- atoi代码实现
- atoi与itoa代码实现
- C函数atoi,itoa的实现代码
- atoi 函数自己写代码实现
- atoi函数介绍与代码实现
- 【练习题】【C】atoi函数的代码实现
- 自己实现的atof()和atoi()代码
- LeetCode(atoi)实现atoi
- atoi实现
- atoi实现
- atoi 实现
- 实现atoi
- atoi实现
- 实现atoi
- atoi实现
- atoi实现
- atoi实现
- 黑马程序员—JAVA基础—io流
- 四川华迪信息技术有限公司 实训 月总结(2015.7)
- [BZOJ2120]数颜色
- Xcode提高编码效率小技巧(一)
- HDOJ 1551 Cable master(二分查找)
- atoi代码实现
- 使用scrapy编写的爬虫
- KMP算法专题-1002
- 常见IO模型
- iOS开发-Day13-OC基础、面向对象
- SOAP request exception
- [BZOJ1996][Hnoi2010]chorus 合唱队
- hdu5326 Work
- sparkR介绍及安装