1 /*
2 *自己写的atoi函数,判断溢出以及最大最小边界值
3 * */
4 #include <iostream>
5 #include <assert.h>
6 #include <climits>
7 using namespace std;
8
9 int myatoi(const char *str)
10 {
11 assert(str!=NULL);
12 int QUO; //quotient 商
13 int REM; //remainder 余数
14 bool sign=true; //判断正负
15 unsigned value=0;
16 while(*str==' '||*str=='\t') //跳过空格
17 ++str;
18 if(*str=='+'||*str=='-')
19 {
20 sign=(*str=='+');
21 ++str;
22 }
23 QUO=sign?INT_MAX/10:-(INT_MIN/10);
24 REM=sign?INT_MAX%10:-(INT_MIN%10)+1;
25 while(*str>='0'&&*str<='9')
26 {
27 if(value>QUO||value==QUO&&*str>REM) //判断溢出
28 return sign?INT_MAX:INT_MIN;
29 value=10*value+*str++-'0';
30 }
31 return sign?value:0-value;
32 }
33
34 int main()
35 {
36 char str[100];
37 cout<<"请输入字符串:";
38 cin.getline(str,100);
39 cout<<myatoi(str)<<endl;
40 return 0;
41 }
自己写的atoi函数
最新推荐文章于 2022-05-26 19:43:17 发布