码迷,mamicode.com
首页 > 其他好文 > 详细

atoi代码实现

时间:2015-07-30 21:25:55      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

atoi函数

atoi函数是实现数字字符串转整型数,实现代码的时候,要特别注意以下几点:

  1. 前面有空格,调过
  2. 要注意符号,即是正还是负数
  3. 非法输入
  4. 处理溢出

代码实现

int my_atoi(const char *str)
{
    const char *s;
    char c;
    unsigned int cutoff;
    int acc;
    int neg, any, cutlim;

    if(str == NULL)
    {
        errno = EINVAL;
        return false;
    }
    s = str;
    do{
        c = *s++;
    }while(c == ‘ ‘ || c == ‘\t‘);

    if(c == ‘-‘){
        neg = 1;
        c = *s++; 
    }
    else
    {
        neg = 0;
        if(c == ‘+‘)
            c = *s++;
    }


    cutoff = neg? INT_MIN : INT_MAX;
    cutlim = cutoff % 10;
    cutoff /= 10;

    acc = any = 0;

    while(c >= ‘0‘ && c <= ‘9‘)
    {
        c -= ‘0‘;
        if(acc > cutoff || (acc == cutoff && c > cutlim))
        {
            any = -1;
            break;
        }
        else
        {
            any = 1;
            acc *= 10;
            acc += c;
        }

        c = *s++;
    }

    if(any < 0)
    {
        errno = ERANGE;
        acc = neg? INT_MIN : INT_MAX;
        return acc;
    }
    else if(any == 0)
    {
        errno = EINVAL;
    }

    else if(neg)
    {
        acc = -acc;
    }

    return acc;
}

测试代码

void Test(const char *str)
{
    errno = -1;
    int result = my_atoi(str);
    if(errno == EINVAL)
        printf("str %s is : EINVAL \n",str);
    else if(errno == ERANGE)
        printf("str %s is : ERANGE  %d \n",str, result);
    else
        printf("str %s is : %d \n",str,result);
}

int main(int argc, char const *argv[])
{
    Test("");

    Test("123");

    Test("+123");

    Test("-123");

    Test("1a33");

    Test("+0");

    Test("-0");

    //有效的最大正整数, 0x7FFFFFFF
    Test("+2147483647");    

    Test("-2147483647");

    Test("+2147483648");

    //有效的最小负整数, 0x80000000
    Test("-2147483648");    

    Test("+2147483649");

    Test("-2147483649");

    Test("+");

    Test("-");

    Test("10522545459");

    Test("-10522545459");

    Test("  +4488");

    Test(" - 321");


    return 0;
}

结果输出如下:

str  is : EINVAL 
str 123 is : 123 
str +123 is : 123 
str -123 is : -123 
str 1a33 is : 1 
str +0 is : 0 
str -0 is : 0 
str +2147483647 is : 2147483647 
str -2147483647 is : -2147483647 
str +2147483648 is : ERANGE  2147483647 
str -2147483648 is : -2147483648 
str +2147483649 is : ERANGE  2147483647 
str -2147483649 is : ERANGE  -2147483648 
str + is : EINVAL 
str - is : EINVAL 
str 10522545459 is : ERANGE  2147483647 
str -10522545459 is : ERANGE  -2147483648 
str   +4488 is : 4488 
str  - 321 is : EINVAL 

参考资料

atoi函数的实现
http://arieshout.me/2012/03/implementation-of-atoi.html

版权声明:本文为博主原创文章,未经博主允许不得转载。

atoi代码实现

标签:

原文地址:http://blog.csdn.net/zwhlxl/article/details/47155963

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!