Facebook :实现atoi函数

本文详细解析了C++中自定义异常类`classCException`的实现及应用,结合`myatoi`函数展示了如何进行字符串到整数的转换,并处理可能遇到的错误情况,包括无效表达式、无效字符和整数溢出。
一、
class CException
{
public:
        CException(const char* str) : m_strErr(str) {}
        string GetErrInfo() { return m_strErr; }
private:
        std::string m_strErr;
};

int myatoi(const char* p)
{
        assert(p);

        int nFlg = 1;
        if ('-' == *p)
                nFlg = -1;

        if ('-' == *p || '+' == *p)
                p++;

        if ('\0' == *p)
                throw CException("Invalid expression");

        int nRet = 0;
        while('\0' != *p)
        {
                if (*p < '0' || *p > '9')
                        throw CException("Invalid character");

                int nVal = *p - '0';
                int nNew = nRet*10 + nFlg * nVal;
                if (nRet != 0 && ((nNew & 0x80000000) != (nRet & 0x80000000)))
                        throw CException("Integer over flow");
                
                nRet = nNew;
                p++;
        }

        return nRet;
}

二、

int atoi (char* str)
{
     assert(str);
     assert(str[0]);
     int result = 0;
     int newResult = 0;
     if (str[0] == '+')
          return atoi(str + 1);
     if (str[0] == '-')
          return -1 * atoi(str + 1);

     int i = 0;

     while (str[i])
     {
          assert(str[i] >= '0' && str[i] <= '9');
          newResult = (result << 1) + (result << 3) + str[i] - '0';
          assert(newResult >= result);
          result = newResult;
          i++;
     }

     return result;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值