国际访客建议访问 Primers 编程伙伴 国际版站点 > C 教程 > atoll 以获得更好的体验。

# C 语言标准库函数 atoll

在头文件 stdlib.h 中定义。
/*********************************************
 * @brief 将字符串转换为 long long 类型的整数
 * @param text 要转换的字符串
 * @return 转换为 long long 类型后的值
 ********************************************/
long long atoll(const char* text);

!subtitle:说明

将字符串转换为 long long 类型的浮点数,仅支持十进制。

此函数会丢弃字符串开头的所有空格字符(由 isspace 函数判断),并提取尽可能多的字符来构成有效的整数。

函数名代表 ASCII to long long

!subtitle:参数

  • text - 要转换的字符串

!subtitle:返回值

  • 返回转换为 long long 类型后的值

  • 失败时返回 0

# 示例

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("%lld\n", atoll("    0123junk"));   // 123
    printf("%lld\n", atoll("    -456junk"));   // 456
    printf("%lld\n", atoll("    2e10"));       // 2,丢弃 e10junk
    printf("%lld\n", atoll("    0xABCD"));     // 0,丢弃 xABCD
    printf("%lld\n", atoll("    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)

本文 更新于: 2025-11-27 09:38:07 创建于: 2025-11-27 09:38:07