atof、 、 _atof_l_wtof_wtof_l

將字串轉換成雙精度浮點數。

語法

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。

備註

這些函式會將字元字串轉換成雙精確度浮點值。

輸入字串是一串字元,可解譯為所指定類型的數值。 函式會在無法辨識為數位一部分的第一個字元停止讀取輸入字串。 此字元可能是終止字串的 Null 字元 ('\0' 或 L'\0')。

atof_wtofstr 引數具有下列形式:

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

whitespace包含會忽略的空間或製表符;sign是加號(+)或減號(-),而且digits是一或多個十進位數。 如果小數點前沒有數字,則在小數點後至少必須要有一個數字。 小數位數的後面可能接著包含簡介字母 (eE) 的指數以及選擇性的帶正負號十進位整數。

這些函式的 UCRT 版本不支援轉換 Fortran 樣式 (dD) 指數字母。 舊版 CRT 支援此非標準延伸模組,而且它可能是您程式碼的重大變更。

這些函 _l 式的後綴版本完全相同,不同之處在於它們使用 locale 傳入的參數,而不是目前的地區設定。

根據預設,此函式的全域狀態會限定於應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態

一般文字常式對應

TCHAR.H 常式 _UNICODE_MBCS 未定義 _MBCS 已定義 _UNICODE 已定義
_tstof atof atof _wtof
_ttof atof atof _wtof

需求

常式 必要的標頭
atof, _atof_l C: <math.h><stdlib.h> C++: <cstdlib><stdlib.h><cmath><math.h>
_wtof, _wtof_l 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

另請參閱

資料轉換
數學與浮點支援
地區設定
_ecvt
_fcvt
_gcvt
setlocale, _wsetlocale
_atodbl、、_atodbl_l_atoldbl_atoldbl_l、、_atoflt_atoflt_l