atoi函数实现

本文探讨了C++中手动实现atoi函数时的溢出判断问题,指出在特定输入情况下,溢出判断可能是不必要的。同时,作者纠正了关于const char* str指针类型的误解,并详细解释了不同类型的指针常量声明方式。
摘要由CSDN通过智能技术生成
下面给出我的atoi实现代码
int aatoii(const char * str)
{
    if(str == NULL) return 0;

    int result = 0;
    int sign = 1;
    if( ('0'<= str[0] && str[0] <= '9') ||(str[0]=='-') || str[0]=='+')
    {
        if(str[0] == '+' || str[0] == '-')
        {
            if(str[0]=='-')
            {
                sign = -1;
            }
            str++;
        }
    }
    else
    {
        return 0;
    }

    while('0'<= *str && *str <= '9')
    {
        result = result*10 + (*str++ - '0');
    }

    return result;
}

修改版:
int aatoii(const char * str)
{
    if(str == NULL) return 0;

    int result = 0;
    int sign = 1;
    if( ('0'<= str[0] && str[0] <= '9') ||(str[0]=='-') || str[0]=='+')
    {
        if(str[0] == '+' || str[0] == '-')
        {
            if(str[0]=='-')
            {
                sign = -1;
            }
            str++;
        }
    }
    
    
    while('0'<= *str && *str <= '9' )
    {
        result = result*10 + (*str++ - '0');
    }

    return result * sign;
}


后面说我没溢出判断:
我仔细想了想:我认为没必有,由于我保证了传进来的str是有意义的:
无外乎这几种情况: {'\0'}, {'+', '\0'}, {'1', '2', '\0'} , {'a', 'b', '1', '2', '\0'},这些都应该没有问题
,由于while('0' <= *str && *str <= '9'),等于间接就判断了。

修改版二:
现在发现我对溢出的理解是错误,下面给出代码

3、今天我才明白const char* str; 是修饰字符串不能改变的,而不是指针, 修饰常量指针的是char* const str;

那我就说说吧:
const int * const pint; //一个const指针,指向一个const成员
const int * pint; //一个非const指针, 指向一个const成员
int *pint; //一个非const指针,指向一个非const成员
int * const pint; //一个const指针,指向一个非const成员
int const * pint; //和第二个一样, 一个非const指针, 指向一个const成员, 这个不常用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值