自己实现的atoi()函数

函数描述:
    将字符串 str 转换成一个整数并返回结果。参数 str  以数字开头,当函数从str 中读到非数字字符则结束转换并将结果返回。

None.gif int atoi(  const  char *str )
ExpandedBlockStart.gif {
InBlock.gif    if (str == 0 ) return 0;
InBlock.gif    
InBlock.gif    int nRet = 0;
InBlock.gif    int nLen = 0;
InBlock.gif    bool bSign = true;
InBlock.gif    bool bFlag = false;
InBlock.gif    
InBlock.gif    nLen = strlen(str);
InBlock.gif    if (nLen == 0) return 0;
InBlock.gif
InBlock.gif    for (int i=0; i<nLen; ++i)
ExpandedSubBlockStart.gif    {
InBlock.gif        if ( str[i] == ' ' && (!bFlag)) continue;
ExpandedSubBlockStart.gif        if ( str[i] >= '0' && str[i] <= '9') { nRet = nRet * 10 + ( str[i] - '0'); bFlag = truecontinue;}
ExpandedSubBlockStart.gif        if ( str[i] == '+' && (!bFlag) ) { bFlag = bSign = truecontinue; }
ExpandedSubBlockStart.gif        if ( str[i] == '-' && (!bFlag) ) { bFlag = true; bSign = falsecontinue; }
InBlock.gif        break;
InBlock.gif        //if ( bFlag && ( str[i] == '+' || str[i] == '-' || str[i] == ' ')) break;
InBlock.gif        
//if ( str[i] < '0' && str[i] > '9' && str[i] != '+' && str[i] != '-' && str[i] != ' ') break;
ExpandedSubBlockEnd.gif
    }
InBlock.gif    if (!bSign) nRet = -nRet;
InBlock.gif    return nRet;
ExpandedBlockEnd.gif}


Edit:2008.09.18
今天和同事讨论这个方法,回过头来看这个方法,发现了这个函数的不足,因此今天重新写了一下,精简临时变量到两个.算法还是以前用到的穷举法.
仔细的去思考了下,减少了不少无用功和不必要的临时变量.
None.gif int ATOI(  const  char *str )
ExpandedBlockStart.gif {
InBlock.gif    if (str == 0 ) return 0;
InBlock.gif    char c;
InBlock.gif    int nRet = -1;
InBlock.gif    for (;;)
ExpandedSubBlockStart.gif    {
InBlock.gif        c = *(str++);
InBlock.gif        if ( c >= '0' && c <= '9')
ExpandedSubBlockStart.gif        {
ExpandedSubBlockStart.gif            if (nRet==0 || nRet==-1) {nRet = c - '0';}// 正数第一个数字
ExpandedSubBlockStart.gif
            else if (nRet==-2) {nRet = -( c - '0');}// 负数第一个数字
InBlock.gif
            else nRet = nRet * 10 + ( c - '0');// 其他数字
InBlock.gif
            continue;
ExpandedSubBlockEnd.gif        }
InBlock.gif        if ( ( (c > 0x08 && c < 0x0E) || c == 0x20) && (nRet==-1)) continue;// 剪掉空白字符
ExpandedSubBlockStart.gif
        if ( c == '+' && (nRet==-1) ) { nRet = 0; continue; }// 正数符号
ExpandedSubBlockStart.gif
        if ( c == '-' && (nRet==-1) ) { nRet = -2; continue; }// 负数符号
InBlock.gif
        if ( (nRet == -1) || (nRet == -2) ) nRet = 0;// 失败返回0值
InBlock.gif
        break;
ExpandedSubBlockEnd.gif    }
InBlock.gif    return nRet;
ExpandedBlockEnd.gif}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值