atoi函数的实现

来源:互联网 发布:天湖ipv6网络电视 编辑:程序博客网 时间:2024/04/29 10:59

系统的atoi函数实现的功能是将一个字符串转化为对应的整型数字,但是值得注意的有以下几点:1.它会过滤掉字符串最前面的一个或者多个空格,2.注意‘+’,‘-’号的处理,3.当数字溢出且为正数时返回INT_MAX,负数返回INT_MIN。以下是具体程序:

#include "stdafx.h"#include<iostream>using namespace std;int my_atoi(const char * input){const int len=strlen(input);int i=0;int sign=1;long long result=0;  //利用long long类型处理溢出情况if (input==nullptr){return result;}while (input[i]==' '&& i<len)   //过滤掉空格{++i;}if (input[i]=='+'){++i;}if (input[i]=='-'){++i;sign=-1;}while(i<len){if (input[i]<'0' || input[i]>'9'){break;}result=result*10+(input[i]-'0')*sign;if (result>INT_MAX){return INT_MAX;}else if (result<INT_MIN){return INT_MIN;}++i;}return result;}int _tmain(int argc, _TCHAR* argv[]){char input[100];while(cin>>input){int result=my_atoi(input);   //自己实现的int resultStandard=atoi(input);  //系统标准的函数cout<<result<<endl;cout<<resultStandard<<endl;}return 0;}
程序运行结果如下:



0 0
原创粉丝点击