您的位置:首页 > 其它

atoi函数简单实现

2016-07-10 12:56 225 查看
1. 看一下atoi函数的要求,通过 man 3 atoi。

原型

#include

   int aoti(const char *str);

描述

    The atoi() function converts the initial portion of the string pointed to bystr to
int representation.

     atoi函数把str字符串初始有效部分转换成int类型。

    因为atoi返回int,出错返回-1是不可取的,因为-1也是有效的,返回0,同样不可取。但是根据其描述,如果str完全无效那么返回的应该是0,否则转换其初始有效部分。

    知道了这些,基本就可以实现了。

点击(此处)折叠或打开

#include

int
my_atoi(const char *str)
{

    int result;

    char sign;

    for (; str && isspace(*str); ++str)

    ; /* 跳过空白,换行,tab*/  

   

    if (!str)
       return 0;

    sign = *str == '+' || *str == '-' ? *str++ : '+'; /* 处理符号 */

    for (result = 0; str && isdigit(*str); ++str) /*转换有效部分 */

        result = result * 10 + *str - '0'; /* FIXME: 没有考虑溢出 */

    return (sign == '+' ? result : -result);

}

标准库实现是调用strol,然后调用strtoul。可以识别八进制,十六进制字符。

IMPLEMENTATION NOTES The atoi() function is
not thread-safe and also not async-cancel safe. Theatoi() function has been deprecated bystrtol()
and should not be used in new code.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: