atoi函数简单实现

来源:互联网 发布:软件开发人员等级 编辑:程序博客网 时间:2024/05/22 02:27
1. 看一下atoi函数的要求,通过 man 3 atoi。

原型
#include
   int aoti(const char *str);

描述
    The atoi() function converts the initial portion of the string pointed to bystr toint representation.
     atoi函数把str字符串初始有效部分转换成int类型。

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

点击(此处)折叠或打开

  1. #include
  2. int
  3. my_atoi(const char *str)
  4. {
  5.     int result;
  6.     char sign;

  7.     for (; str && isspace(*str); ++str)
  8.     ; /* 跳过空白,换行,tab*/  
  9.    
  10.     if (!str)
  11.        return 0;
  12.     sign = *str == '+' || *str == '-' ? *str++ : '+'; /* 处理符号 */

  13.     for (result = 0; str && isdigit(*str); ++str) /*转换有效部分 */
  14.         result = result * 10 + *str - '0'; /* FIXME: 没有考虑溢出 */
  15.     return (sign == '+' ? result : -result);
  16. }

标准库实现是调用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.
0 0