/*********************************************
* @brief 将字符串转换为 long 类型的整数
* @param text 要转换的字符串
* @return 转换为 long 类型后的值
********************************************/
long atol(const char* text);
!subtitle:说明
将字符串转换为 long 类型的浮点数,仅支持十进制。
此函数会丢弃字符串开头的所有空格字符(由 isspace 函数判断),并提取尽可能多的字符来构成有效的整数。
函数名代表
ASCII to long。
!subtitle:参数
text - 要转换的字符串
!subtitle:返回值
返回转换为 long 类型后的值
失败时返回 0
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("%ld\n", atol(" 0123junk")); // 123
printf("%ld\n", atol(" -456junk")); // 456
printf("%ld\n", atol(" 2e10")); // 2,丢弃 e10junk
printf("%ld\n", atol(" 0xABCD")); // 0,丢弃 xABCD
printf("%ld\n", atol(" 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.3 The atol function