#C 语言标准库函数 strtof
/*********************************************
* @brief 将字符串转换为 float 类型的浮点数
* @param start 要转换的字符串
* @param[out] end 返回成功转换的子串后下一个字符的地址
* @return 转换为 float 类型后的值
********************************************/
float strtof(const char* restrict start, char** restrict end);
说明
将字符串转换为 float 类型的浮点数。
此函数会丢弃字符串开头的所有空格字符(由 isspace 函数判断),并提取尽可能多的字符来构成有效的浮点数。
支持正负号、十进制数、0x 或 0X 开头的十六进制数、e 或 E 表示的科学计数法、INF 或 INFINITY(忽略大小写)、NAN(忽略大小写)。
参数
start- 要转换的字符串end- 返回成功转换的子串后下一个字符的地址
例如:
返回值
- 返回转换为
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