std::strtof, std::strtod, std::strtold
来自cppreference.com
在标头 <cstdlib> 定义 | ||
float strtof (constchar* str, char** str_end ); | (1) | (C++11 起) |
double strtod (constchar* str, char** str_end ); | (2) | |
longdouble strtold(constchar* str, char** str_end ); | (3) | (C++11 起) |
转译 str 所指向的字节字符串中的浮点数。
函数会舍弃任何空白符(由 std::isspace() 确定),直至找到首个非空白符。然后它会取用尽可能多的字符,以构成合法的浮点数表示,并将它们转换成浮点值。合法的浮点值可以为下列之一:
- 十进制浮点数表达式。它由下列部分组成:
- (可选) 正或负号
- 非空的十进制数字序列,可选地包含一个小数点字符(由当前的 C 本地环境确定)(定义有效数字)
- (可选)
e
或E
,并跟随可选的正或负号,以及非空十进制数字序列(以 10 为底定义指数)
| (C++11 起) |
- 任何其他可由当前 C 本地环境接受的表达式。
函数设置 str_end 所指向的指针指向最后被转译字符的后一字符,若 str_end 为空指针,则忽略它。
目录 |
[编辑]参数
str | - | 指向要转译的空终止字节字符串的指针 |
str_end | - | 指向指向字符指针的指针。 |
[编辑]返回值
成功时为对应 str 内容的浮点数。若转换出的值落在对应返回类型的范围外,则发生值域错误并返回 HUGE_VAL、HUGE_VALF 或 HUGE_VALL。若无法进行转换,则返回 0 并将 *str_end 设为 str。
[编辑]示例
运行此代码
#include <cerrno>#include <clocale>#include <cstdlib>#include <iostream>#include <string> int main(){constchar* p ="111.11 -2.22 0X1.BC70A3D70A3D7P+6 -Inf 1.18973e+4932zzz";char* end{};std::cout<<"解析 \""<< p <<"\":\n";errno=0;for(double f = std::strtod(p, &end); p != end; f = std::strtod(p, &end)){std::cout<<" '"<<std::string(p, end - p)<<"' -> "; p = end;if(errno==ERANGE){std::cout<<"值域错误, 得到 ";errno=0;}std::cout<< f <<'\n';} if(std::setlocale(LC_NUMERIC, "de_DE.utf8")){std::cout<<"de_DE.utf8 本地环境中:\n";std::cout<<" '123.45' -> "<< std::strtod("123.45", 0)<<'\n';std::cout<<" '123,45' -> "<< std::strtod("123,45", 0)<<'\n';}}
可能的输出:
解析 "111.11 -2.22 0X1.BC70A3D70A3D7P+6 -Inf 1.18973e+4932zzz": '111.11' -> 111.11 ' -2.22' -> -2.22 ' 0X1.BC70A3D70A3D7P+6' -> 111.11 ' -Inf' -> -inf ' 1.18973e+4932' -> 值域错误, 得到 inf de_DE.utf8 本地环境中: '123.45' -> 123 '123,45' -> 123.45
[编辑]参阅
转换字节字符串为浮点数 (函数) | |
转换宽字符串为浮点数 (函数) | |
(C++17) | 转换字符序列到整数或浮点数 (函数) |
strtof, strtod, strtold 的 C 文档 |