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

# C 语言标准库函数 strtof

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

!subtitle:说明

将字符串转换为 float 类型的浮点数。

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

支持正负号、十进制数、0x0X 开头的十六进制数、eE 表示的科学计数法、INFINFINITY(忽略大小写)、NAN(忽略大小写)。

!subtitle:参数

  • start - 要转换的字符串

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

例如:

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

!subtitle:返回值

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

  • 失败时返回 0.0

# 示例

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

int main(void)
{
    const char* text = "3.1415926   2.71828   Inf   0xABCD   2e10"; // 包含多个数值的字符串
    const char* start = text;   // 开头
    char* end = NULL;     // 结尾

    while (1)
    {
        float num = strtof(start, &end);  // 进行转换
        if (start == end)
            break;

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

说明:

调用轮次 调用前 start 指向 调用后 end 指向
1 "3.1415926 2.71828 Inf 0xABCD 2e10" " 2.71828 Inf 0xABCD 2e10"
2 " 2.71828 Inf 0xABCD 2e10" " Inf 0xABCD 2e10"
3 " Inf 0xABCD 2e10" " 0xABCD 2e10"
4 " 0xABCD 2e10" " 2e10"
5 " 2e10" ""
6 "" ""

运行结果:

3.141593
2.718280
inf
43981.000000
20000000000.000000

# 推荐阅读

# 参考标准

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

    • 7.22.1.3 The strtod, strtof, and strtold functions (p: TBD)

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

    • 7.22.1.3 The strtod, strtof, and strtold functions (p: 249-251)

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

    • 7.22.1.3 The strtod, strtof, and strtold functions (p: 342-344)

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

    • 7.20.1.3 The strtod, strtof, and strtold functions (p: 308-310)

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

    • 4.10.1.4 The strtod function

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