自己写的atoi函数

  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 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值