strtof, _strtof_l, wcstof, _wcstof_l

将字符串转换为单精度浮点值。

语法

float strtof(
   const char *strSource,
   char **endptr
);
float _strtof_l(
   const char *strSource,
   char **endptr,
   _locale_t locale
);
float wcstof(
   const wchar_t *strSource,
   wchar_t **endptr
);
float wcstof_l(
   const wchar_t *strSource,
   wchar_t **endptr,
   _locale_t locale
);

参数

strSource
要转换的 null 终止的字符串。

endptr
指向停止扫描的字符的指针。

locale
要使用的区域设置。

返回值

strtof 返回浮点数值,只有当表示形式会导致溢出时,该函数才返回 +/-HUGE_VALFHUGE_VALF 的符号与无法表示的值的符号相匹配。 如果无法执行转换或出现下溢,则 strtof 返回 0。

wcstof 返回类似于 strtof 的值。 对于这两个函数,如果发生溢出或下溢,则将 errno 设置为 ERANGE,并调用无效的参数处理程序,如参数验证中所述。

有关返回代码的详细信息,请参阅 errno_doserrno_sys_errlist_sys_nerr

注解

每个函数均将输入字符串 strSource 转换为 floatstrtof 函数将 strSource 转换为单精度值。 strtof 在首个无法识别为数字一部分的字符处停止读取字符串 strSource。 此字符可能是终止 null 字符。 wcstofstrtof 的宽字符版本;它的 strSource 参数是宽字符字符串。 否则,这些函数具有相同行为。

默认情况下,此函数的全局状态范围限定为应用程序。 若要更改此行为,请参阅 CRT 中的全局状态

一般文本例程映射

TCHAR.H 例程 _UNICODE_MBCS 未定义 _MBCS 已定义 _UNICODE 已定义
_tcstof strtof strtof wcstof
_tcstof_l _strtof_l _strtof_l _wcstof_l

当前区域设置的 LC_NUMERIC 类别设置确定 strSource 中的基数字符的识别;有关详细信息,请参阅 setlocale_wsetlocale。 不带有 _l 后缀的函数使用当前区域设置;带有该后缀的函数同样如此,只不过它们使用传递的区域设置。 有关详细信息,请参阅 Locale

如果 endptr 不为 NULL,则在 endptr 所指向的位置存储指向字符的指针(该指针停止扫描)。 如果不能执行任何转换(未找到任何有效的数字或指定了无效的基数),则将 strSource 的值存储在由 endptr 指向的位置。

strtof 需要 strSource 指向以下形式的字符串:

[whitespace] [sign] [digits] [.digits] [{e | E} [sign] digits]

whitespace 可能包含被忽略的空格和制表符;sign 是加号 (+) 或减号 (-);digits 是一个或多个十进制数字。 如果基数字符前没有任何数字,则基数字符后必须至少有一个数字。 十进制数字后面可以跟一个指数,可由一个介绍性字母(eE)和一个可选的有符号整数组成。 如果指数部分和基数字符都没有出现,则假定基数字符跟随字符串中的最后一个数字。 不符合此形式的第一个字符将停止扫描。

这些函数的 UCRT 版本不支持转换 Fortran 样式的(dD)指数字母。 这个非标准扩展受早期版本的 CRT 支持,可能会为你的代码的带来重大变化。

要求

例程 必需的标头
strtof_strtof_l C:<stdlib.h> C++:<cstdlib> 或 <stdlib.h>
wcstof_wcstof_l C:<stdlib.h> 或 <wchar.h> C++:<cstdlib>、<stdlib.h> 或 <wchar.h>

有关兼容性的详细信息,请参阅 兼容性

示例

// crt_strtof.c
// This program uses strtof to convert a
// string to a single-precision value.

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

int main( void )
{
   char *string;
   char *stopstring;
   float x;

   string = "3.14159This stopped it";
   x = strtof(string, &stopstring);
   printf("string = %s\n", string);
   printf("   strtof = %f\n", x);
   printf("   Stopped scan at: %s\n\n", stopstring);
}
string = 3.14159This stopped it
   strtof = 3.141590
   Stopped scan at: This stopped it

另请参阅

数据转换
数学和浮点支持
多字节字符序列的解释
区域设置
字符串到数值函数
strtod_strtod_lwcstod_wcstod_l
strtolwcstol_strtol_l_wcstol_l
strtoul_strtoul_lwcstoul_wcstoul_l
atof_atof_l_wtof_wtof_l
localeconv
_create_locale_wcreate_locale
_free_locale