#C 语言标准库函数 atoi
/*********************************************
* @brief 将字符串转换为 int 类型的整数
* @param text 要转换的字符串
* @return 转换为 int 类型后的值
********************************************/
int atoi(const char* text);
说明
将字符串转换为 int
类型的浮点数,仅支持十进制。
此函数会丢弃字符串开头的所有空格字符(由 isspace 函数判断),并提取尽可能多的字符来构成有效的整数。
函数名代表
ASCII to int
。
参数
text
- 要转换的字符串
返回值
- 返回转换为
int
类型后的值 - 失败时返回 0
#示例
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("%d\n", atoi(" 0123junk")); // 123
printf("%d\n", atoi(" -456junk")); // 456
printf("%d\n", atoi(" 2e10")); // 2,丢弃 e10junk
printf("%d\n", atoi(" 0xABCD")); // 0,丢弃 xABCD
printf("%d\n", atoi(" junk")); // 失败
return 0;
}
说明:
0123junk
以十进制而非八进制解析,其中junk
被丢弃2e10
以十进制解析, 保留2
丢弃e10
0xABCD
以十进制解析, 保留0
丢弃xABCD
junk
解析失败返回 0
运行结果:
123 -456 2 0 0
#推荐阅读
#参考标准
- C23 standard (ISO/IEC 9899:2024):
- 7.22.1.2 The atoi, atol, and atoll functions (p: TBD)
- C17 standard (ISO/IEC 9899:2018):
- 7.22.1.2 The atoi, atol, and atoll functions (p: 249)
- C11 standard (ISO/IEC 9899:2011):
- 7.22.1.2 The atoi, atol, and atoll functions (p: 341)
- C99 standard (ISO/IEC 9899:1999):
- 7.20.1.2 The atoi, atol, and atoll functions (p: 307)
- C89/C90 standard (ISO/IEC 9899:1990):
- 4.10.1.2 The atoi function