atoi源代码的溢出问题,自己写了个程序 可以防止溢出 让atoi限制在0-65535

atoi源代码的溢出问题,自己写了个程序 可以防止溢出 让atoi限制在0-65535,当然改一下也可以限制在INT_MAX和INT_MIN之间。 

写在这里是为了以后用到的话没地方找,或者给一些需要的朋友参考。本人水平有限,不足之处请指出

下面贴上代码


#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>




int myatoi(const char *nptr);


int a,b,c,d;
char * aa = "TO -12345678910111213";
int main()
{
    a=1;b=2;c=3;d=4;
    a=a+b;
    b=INT_MAX;
    d=a+102;
    a=myatoi(&aa[2]);
    if(a>65535)
        a=65535;
    else if(a< 0)
        a=0;
    printf("Hello world!\n");
    return 0;
}


int myatoi(const char *nptr)
{
int c=0;
int total=0;
int sign=0;


while( isspace((int)(unsigned char)*nptr))
    ++nptr;


c=(int)(unsigned char)*nptr;
sign=c;
if(c=='-'|| c=='+')
    c=(int)(unsigned char)*nptr++;
total=0;
while(isdigit(c))
{
    total = 10*total + (c - '0');
    if(total >= (INT_MAX/10) )
        return total;
    else if(total < 0)
        return 0;
    c=(int)(unsigned char)*(++nptr);
}


if(sign == '-')
    return -total;
else
    return total;


}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值