博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
atoi 实现
阅读量:7171 次
发布时间:2019-06-29

本文共 1423 字,大约阅读时间需要 4 分钟。

int atoi(const char *nptr);

把字符串转换成整型数。ASCII to integer 的缩写。

头文件: #include <stdlib.h>

参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。否则,返回零,

1 #include 
2 #include
3 4 //参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。否则,返回零 5 int atoi(const char *nptr) 6 { 7 if (!nptr) //空字符串 8 return 0; 9 10 int p = 0;11 while(isspace(nptr[p])) //清除空白字符12 p++;13 14 if (isdigit(nptr[p]) || '+' == nptr[p] || '-' == nptr[p]) //清除后第一个是数字相关15 {16 int res = 0;17 bool flag = true; //正负数标志18 19 //对第一个数字相关字符的处理20 if('-' == nptr[p])21 flag = false;22 else if('+' != nptr[p])23 res = nptr[p] - '0';24 25 //处理剩下的26 p++;27 while(isdigit(nptr[p]))28 {29 res = res * 10 + (nptr[p] - '0');30 p++;31 }32 33 if(!flag) //负数34 res = 0 - res;35 return res;36 } 37 else38 {39 return 0;40 }41 }42 int main() 43 { 44 using std::cin;45 using std::cout;46 using std::endl;47 48 cout << atoi("213") <
<< atoi("+2134") << endl << atoi("-342") <
<< atoi(" -45d") << endl49 <

转载于:https://www.cnblogs.com/jiayith/p/3912629.html

你可能感兴趣的文章
删除数据库
查看>>
python第二周
查看>>
c易错
查看>>
答复功能改进建议
查看>>
(七)UML之用例图
查看>>
数据库简介
查看>>
swoole使用协程
查看>>
BNU OJ 51003 BQG's Confusing Sequence
查看>>
LightOJ 1422 Halloween Costumes
查看>>
动态子类化CComboBox以得到子控件EDIT及LISTBOX
查看>>
设计模式-单例模式
查看>>
8. String to Integer (atoi)
查看>>
cocos2dx内存优化
查看>>
Arguments
查看>>
鲁棒图(Robustness Diagram)
查看>>
2011TG初赛
查看>>
css3各种loading写法
查看>>
android 获取资源文件 R.drawable中的图片转换为drawable、bitmap(转载)
查看>>
GOOGLE卫星地图URL中的Tile位置编码算法
查看>>
python3中如何区分一个函数和方法
查看>>