atoi
是 C 标准库中的一个函数,用于将字符串转换为整数。它的全称是 "ASCII to Integer"。以下是 atoi
函数的用法详解:
函数原型
```c
include
int atoi(const char *str);
```
参数
str
:指向要转换的 C 风格字符串的指针。该字符串应表示一个有效的整数,可以包含可选的前导空白字符(如空格、制表符),可选的符号(+
或-
),然后是数字字符。
返回值
- 如果转换成功,
atoi
返回转换后的整数值。 - 如果没有可转换的数字(例如字符串不包含数字部分),
atoi
返回 0。 atoi
不会检测溢出,如果结果超出int
类型的范围,行为是未定义的。
注意事项
- 错误处理:
atoi
不提供错误检测机制,例如无法区分输入字符串为 "0" 和没有有效数字的情况。对于更健壮的错误处理,建议使用strtol
或strtoul
等函数。 - 溢出问题:由于
atoi
不检查溢出,输入可能导致未定义行为。例如,如果字符串表示的数字超出int
的范围,结果可能不正确。 - 空指针:如果传入空指针(
NULL
),行为是未定义的。
示例代码
```c
include
include
int main() {
const char *str1 = "12345";
const char *str2 = " -6789";
const char *str3 = "42abc"; // 只有前面的数字会被转换
const char *str4 = "abc42"; // 无法转换,返回 0
int num1 = atoi(str1);
int num2 = atoi(str2);
int num3 = atoi(str3);
int num4 = atoi(str4);
printf("Converted '%s' to %d\n", str1, num1);
printf("Converted '%s' to %d\n", str2, num2);
printf("Converted '%s' to %d\n", str3, num3);
printf("Converted '%s' to %d\n", str4, num4);
return 0;
}
```
输出
Converted '12345' to 12345
Converted ' -6789' to -6789
Converted '42abc' to 42
Converted 'abc42' to 0
替代方案
由于 atoi
的局限性,通常建议使用 strtol
,它提供了更好的错误检测和范围检查。例如:
```c
include
include
include
include
int main() {
const char *str = "12345";
char *endptr;
errno = 0; // 清除全局错误标志
long value = strtol(str, &endptr, 10);
if ((errno == ERANGE && (value == LONG_MAX || value == LONG_MIN))
|| (errno != 0 && value == 0)) {
perror("strtol");
} else if (endptr == str) {
printf("No digits were found\n");
} else {
printf("Converted '%s' to %ld\n", str, value);
}
return 0;
}
```
strtol
提供了更细粒度的控制和错误检测,适合处理更复杂的输入场景。
(www.nzw6.com)