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

# C 语言标准库函数 strtoul

在头文件 stdlib.h 中定义。
/*********************************************
 * @brief 将字符串转换为 unsigned long 类型的浮点数
 * @param start 要转换的字符串
 * @param[out] end 返回成功转换的子串后下一个字符的地址
 * @param base 进制基数
 * @return 转换为 unsigned long 类型后的值
 ********************************************/
unsigned long strtoul(const char* restrict start, char** restrict end, int base);

!subtitle:说明

将字符串转换为 unsigned long 类型的整数。

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

支持正负号、十进制数、0 开头的八进制数、0x0X 开头的十六进制数。

!subtitle:参数

  • start - 要转换的字符串

  • end - 返回成功转换的子串后下一个字符的地址

  • base - 进制基数,最大支持 36 进制,设为 0 时自动检测基数

例如:

flowchart TB
    subgraph 字符串
        m0["2"]
        m1["3"]
        m2["3"]
        m3["(空格)"]
        m4["(空格)"]
        m5["6"]
        m6["6"]
        m7["6"]
    end
    
    start_ptr["start"] --> m0
    end_ptr["end"] --> m3

!subtitle:返回值

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

  • 失败时返回 0

# 示例

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

int main(void)
{
    const char* text = "233  666  888  010  0x10"; // 包含多个数值的字符串
    const char* start = text;   // 开头
    char* end = NULL;     // 结尾

    while (1)
    {
        unsigned long num = strtoul(start, &end, 0);  // 进行转换,自动检测进制基数
        if (start == end)
            break;

        printf("%lu\n", num);    // 打印
        start = end;            // 指向下一个数值
    }
    
    return 0;
}

说明:

调用轮次 调用前 start 指向 调用后 end 指向
1 "233 666 888 010 0x10" " 666 888 010 0x10"
2 " 666 888 010 0x10" " 888 010 0x10"
3 " 888 010 0x10" " 010 0x10"
4 " 010 0x10" " 0x10"
5 " 0x10" ""
6 "" ""

运行结果:

233
666
888
8
16

# 推荐阅读

# 参考标准

  • C23 standard (ISO/IEC 9899:2024):

    • 7.24.1.7 The strtol, strtoll, strtoul, and strtoull functions (p: TBD)

  • C17 standard (ISO/IEC 9899:2018):

    • 7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 251-252)

  • C11 standard (ISO/IEC 9899:2011):

    • 7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 344-345)

  • C99 standard (ISO/IEC 9899:1999):

    • 7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 310-311)

  • C89/C90 standard (ISO/IEC 9899:1990):

    • 4.10.1.6 The strtoul function

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