将字符串转换为双精度型。
语法
double atof(
   const char *str
);
double _atof_l(
   const char *str,
   _locale_t locale
);
double _wtof(
   const wchar_t *str
);
double _wtof_l(
   const wchar_t *str,
   _locale_t locale
);
参数
str
要转换的字符串。
locale
要使用的区域设置。
返回值
每个函数均返回 double 值,此值是通过将输入字符解释为数字来生成的。 如果输入无法转换为该类型的值,则返回值为 0.0。
在所有超出范围的情况下,将 errno 设置为 ERANGE。 如果传入的参数为 NULL,则调用无效参数处理程序,如参数验证中所述。 如果允许执行继续,则这些功能将 errno 设置为 EINVAL,并返回 0。
备注
这些函数将字符串转换为双精度浮点值。
输入字符串是一系列字符,可以解释为指定类型的数值。 该函数在首个它无法识别为数字组成部分的字符处停止读取输入字符串。 此字符可能是终止字符串的空字符('\0' 或 L'\0')。
atof 和 _wtof 的 str 参数采用以下格式:
whitespace 由空格或制表符组成,将被忽略;sign 是加号 (+) 或减号 (-);digits 是一个或多个十进制数字。 如果小数点前没有数字,则小数点后必须至少有一个数字。 十进制数字后面可以跟一个指数,该指数由一个引导性字母(e 或 E)和一个可选的带符号十进制整数组成。
这些函数的 UCRT 版本不支持转换 Fortran 样式的(d 或 D)指数字母。 这个非标准扩展受早期版本的 CRT 支持,可能会为你的代码的带来重大变化。
这些带有 _l 后缀的函数的版本相同,只不过它们使用传入的 locale 参数而不是当前区域设置。
默认情况下,此函数的全局状态范围限定为应用程序。 若要更改此行为,请参阅 CRT 中的全局状态。
一般文本例程映射
| TCHAR.H例程 | _UNICODE和_MBCS未定义 | _MBCS已定义 | _UNICODE已定义 | 
|---|---|---|---|
| _tstof | atof | atof | _wtof | 
| _ttof | atof | atof | _wtof | 
要求
| 例程 | 必需的标头 | 
|---|---|
| %> | C: <math.h>或<stdlib.h>C++:<cstdlib>、<stdlib.h>、<cmath>或<math.h> | 
| %> | C: <stdlib.h>或<wchar.h>C++:<cstdlib>、<stdlib.h>或<wchar.h> | 
示例
此程序说明如何使用 atof 和 _atof_l 函数将存储为字符串的数字转换为数值。
// crt_atof.c
//
// This program shows how numbers stored as
// strings can be converted to numeric
// values using the atof and _atof_l functions.
#include <stdlib.h>
#include <stdio.h>
#include <locale.h>
int main(void)
{
    char    *str = NULL;
    double value = 0;
    _locale_t fr = _create_locale(LC_NUMERIC, "fr-FR");
    // An example of the atof function
    // using leading and training spaces.
    str = "  3336402735171707160320 ";
    value = atof(str);
    printf("Function: atof(\"%s\") = %e\n", str, value);
    // Another example of the atof function
    // using the 'E' exponential formatting keyword.
    str = "3.1412764583E210";
    value = atof(str);
    printf("Function: atof(\"%s\") = %e\n", str, value);
    // An example of the atof and _atof_l functions
    // using the 'e' exponential formatting keyword
    // and showing different decimal point interpretations.
    str = "  -2,309e-25";
    value = atof(str);
    printf("Function: atof(\"%s\") = %e\n", str, value);
    value = _atof_l(str, fr);
    printf("Function: _atof_l(\"%s\", fr)) = %e\n", str, value);
}
Function: atof("  3336402735171707160320 ") = 3.336403e+21
Function: atof("3.1412764583E210") = 3.141276e+210
Function: atof("  -2,309e-25") = -2.000000e+00
Function: _atof_l("  -2,309e-25", fr)) = -2.309000e-25