Chinaunix首页 | 论坛 | 博客
  • 博客访问: 82651
  • 博文数量: 18
  • 博客积分: 454
  • 博客等级: 下士
  • 技术积分: 237
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-03 13:38
文章分类

全部博文(18)

文章存档

2012年(18)

分类: LINUX

2012-06-02 17:06:01

1. 看一下atoi函数的要求,通过 man 3 atoi。

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

描述
    The atoi() function converts the initial portion of the string pointed to by str to int 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. The atoi() function has been deprecated by strtol() and should not be used in new code.

阅读(9330) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

luoops2013-11-16 09:00:59

请问下这个函数返回局部变量?