atoi, atol, atoll
来自cppreference.com
在标头 <stdlib.h> 定义 | ||
int atoi (constchar* str ); | (1) | |
long atol (constchar* str ); | (2) | |
longlong atoll(constchar* str ); | (3) | (C99 起) |
转换 str 所指的字节字符串中的整数。隐含的基数总为 10。
舍弃任何空白符,直至找到首个非空白符,然后接收尽可能多的字符以组成合法的整数表示,并转换之为整数。合法的整数含下列部分:
- (可选) 正或负号
- 数位
如果结果的值无法被表示,即转换后的值落在对应返回类型之外,则其行为未定义。
目录 |
[编辑]参数
str | - | 指向要转译的空终止字符串的指针 |
[编辑]返回值
成功时为对应于 str 的内容的整数。若转换的值落在对应的返回类型范围外,则返回值未定义。
若无法进行转换,则返回 0。
[编辑]注解
其名字代表“ASCII to integer”。
[编辑]示例
运行此代码
#include <stdio.h>#include <stdlib.h> int main(void){printf("%i\n", atoi(" -123junk"));printf("%i\n", atoi(" +321dust"));printf("%i\n", atoi("0"));printf("%i\n", atoi("0042"));// 当做代用前导零的十进制数printf("%i\n", atoi("0x2A"));// 仅转换前导零,丢弃 "x2A"printf("%i\n", atoi("junk"));// 无可进行的转换printf("%i\n", atoi("2147483648"));// UB:在 int 范围外}
可能的输出:
-123 321 0 42 0 0 -2147483648
[编辑]引用
- C23 标准(ISO/IEC 9899:2024):
- 7.22.1.2 The atoi, atol, and atoll functions (第 TBD 页)
- C17 标准(ISO/IEC 9899:2018):
- 7.22.1.2 The atoi, atol, and atoll functions (第 249 页)
- C11 标准(ISO/IEC 9899:2011):
- 7.22.1.2 The atoi, atol, and atoll functions (第 341 页)
- C99 标准(ISO/IEC 9899:1999):
- 7.20.1.2 The atoi, atol, and atoll functions (第 307 页)
- C89/C90 标准(ISO/IEC 9899:1990):
- 4.10.1.2 The atoi function
- 4.10.1.3 The atol function
[编辑]参阅
(C99) | 将字节字符串转换成整数 (函数) |
(C99) | 将字节字符串转换成无符号整数 (函数) |
(C95)(C99) | 转换宽字符串为整数 (函数) |
(C95)(C99) | 转换宽字符串为无符号整数 (函数) |
atoi, atol, atoll 的 C++ 文档 |