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.
原型
#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.
相关文章推荐
- C语言atoi()函数:将字符串转换成int(整数)
- Express 摘录 (1)
- atoi()
- linux中服务器定时程序设定
- exce()族
- FD_CLOEXEC是什么?
- Android开发之Error when loading the SDK
- C语言link()函数:建立文件连接
- 2016重拾linux碎片
- 【HDU】5451 Best Solver(2015 ACM/ICPC Shenyang Online)
- pread,pwrite,read,write区别
- git fetch
- linux编程学习笔记(八) 文件 定位 lseek pread pwrite
- C语言lseek()函数:移动文件的读写位置
- S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP 分别是什么意思?
- 轻松应用Linux连接校园网
- 树上(带修改)莫队算法-- bzoj4129 && bzoj3757
- 用Javascript控制Table的行移动
- 详细介绍Linux指令od
- Unity2D开发小细节