strtof, strtod, strtold

来自cppreference.com
< c‎ | string‎ | byte
在标头 <stdlib.h> 定义
float       strtof (constchar*restrict str, char**restrict str_end );
(1) (C99 起)
(2)
double      strtod (constchar*          str, char**          str_end );
(C99 前)
double      strtod (constchar*restrict str, char**restrict str_end );
(C99 起)
longdouble strtold(constchar*restrict str, char**restrict str_end );
(3) (C99 起)

转译 str 所指向的字节字符串中的浮点数。

函数会舍弃任何空白符(由 isspace 确定),直至找到首个非空白符。然后它会取用尽可能多的字符,以构成合法的浮点数表示,并将它们转换成浮点值。合法的浮点值可以为下列之一:

  • 十进制浮点数表达式。它由下列部分组成:
  • (可选) 正或负号
  • 非空的十进制数字序列,可选地包含一个小数点字符(由当前的 C 本地环境确定)(定义有效数字)
  • (可选)eE,并跟随可选的正或负号,以及非空十进制数字序列(以 10 为底定义指数)
  • 十六进制浮点数表达式。它由下列部分组成:
  • (可选) 正或负号
  • 0x0X
  • 非空的十六进制数字序列,选地包含一个小数点字符(由当前的 C 本地环境确定)(定义有效数字)
  • (可选)pP,并跟随可选的正或负号,以及非空十进制数字序列(以 2 为底定义指数)
  • 无穷大表达式。它由下列部分组成:
  • (可选) 正或负号
  • INFINFINITY,忽略大小写
  • 非数(NaN)表达式。它由下列部分组成:
  • (可选) 正或负号
  • NANNAN(char_sequence ),忽略 NAN 部分的大小写。 char_sequence 只能由数字、拉丁字母和下划线构成。结果是一个静态的 NaN 浮点值。
(C99 起)
  • 任何其他可由当前 C 本地环境接受的表达式。

函数设置 str_end 所指向的指针指向最后被转译字符的后一字符,若 str_end 为空指针,则忽略它。

目录

[编辑]参数

str - 指向要转译的空终止字节字符串的指针
str_end - 指向指向字符指针的指针

[编辑]返回值

成功时为对应 str 内容的浮点数。若转换出的值落在对应返回类型的范围外,则发生值域错误(将 errno 设为 ERANGE)并返回 HUGE_VALHUGE_VALFHUGE_VALL。若无法进行转换,则返回 0 并将 *str_end 设为 str

[编辑]示例

#include <errno.h>#include <stdio.h>#include <stdlib.h>   int main(void){// 带错误处理的解析constchar* p ="111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz";printf("Parsing '%s':\n", p);char* end =NULL;for(double f = strtod(p, &end); p != end; f = strtod(p, &end)){printf("'%.*s' -> ", (int)(end - p), p); p = end;if(errno==ERANGE){printf("range error, got ");errno=0;}printf("%f\n", f);}   // 无错误处理的解析printf("\" -0.0000000123junk\" -->  %g\n", strtod(" -0.0000000123junk", NULL));printf("\"junk\" -->  %g\n", strtod("junk", NULL));}

可能的输出:

Parsing '111.11 -2.22 Nan inF 0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz': '111.11' -> 111.110000 ' -2.22' -> -2.220000 ' Nan' -> nan ' nan(2)' -> nan ' inF' -> inf ' 0X1.BC70A3D70A3D7P+6' -> 111.110000 ' 1.18973e+4932' -> range error, got inf " -0.0000000123junk" --> -1.23e-08 "junk" --> 0

[编辑]引用

  • C23 标准(ISO/IEC 9899:2024):
  • 7.22.1.3 The strtod, strtof, and strtold functions (第 TBD 页)
  • C17 标准(ISO/IEC 9899:2018):
  • 7.22.1.3 The strtod, strtof, and strtold functions (第 249-251 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.22.1.3 The strtod, strtof, and strtold functions (第 342-344 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.20.1.3 The strtod, strtof, and strtold functions (第 308-310 页)
  • C89/C90 标准(ISO/IEC 9899:1990):
  • 4.10.1.4 The strtod function

[编辑]参阅

将字节字符串转换成浮点数
(函数)[编辑]
(C99)(C95)(C99)
转换宽字符串为浮点数
(函数)[编辑]
strtof, strtod, strtold 的 C++ 文档
close