正文开始
1. atoi函数的介绍
1.1 函数功能
atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数,应用在计算机程序和办公软件中。int atoi(const char *str) 函数会扫描参数 str字符串,会跳过前面的空白字符(例如空格,tab缩进)等。如果 str不能转换成 int 或者 str为空字符串,那么将返回 0 [1]。特别注意,该函数要求被转换的字符串是按十进制数理解的。atoi输入的字符串对应数字存在大小限制(与int类型大小有关),若其过大可能报错-1。
注:使用时需包含 <cstdlib.h>头文件
1.2 参数
参数:
str
以整数表示形式开头的C字符串。
1.3 返回值
成功后,函数将转换后的整数作为int值返回。
如果转换后的值超出了int可表示值的范围,则会导致未定义的行为。如果可能的话,请参阅strtol以获得更健壮的跨平台替代方案。
1.4 例子
/* atoi example */
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atoi */
int main ()
{
int i;
char buffer[256];
printf ("Enter a number: ");
fgets (buffer, 256, stdin);
i = atoi (buffer);
printf ("The value entered is %d. Its double is %d.\n",i,i*2);
return 0;
}
结果:
1.5 数据竞赛
访问str指向的数组。
1.6 例外(C++)
无抛出保证:此函数从不抛出异常。
如果str没有指向有效的C字符串,或者转换后的值超出了int表示的值的范围,则会导致未定义的行为。
2. 函数模拟实现
2.1 标准编译
我们设计就是跳过空格,允许‘+’、‘-’的控制,将字符串的内容转化为整数。
#include<stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
int my_atoi(const char* str)
{
//首先跳过空格
int n = 0, neg = 0;
while (isspace(*str))
str++;
//控制正负
switch (*str)
{
case'-':neg = 1;
case'+':str++;
}
//compute n as a negative number to avoid overflow on int_min*
输出数值
while (isdigit(*str))
n = 10 * n - (*str++ - '0');
return neg ? n : -n;
}
int main()
{
int i;
char buffer[256];
printf ("Enter a number: ");
fgets (buffer, 256, stdin);
i = my_atoi (buffer);
printf ("The value entered is %d. Its double is %d.\n",i,i*2);
return 0;
}
完!