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
和 _wtof
的 str
引數具有下列形式:
[whitespace
] [sign
] [digits
] [.
digits
] [ {e
| E
}[sign
]digits
]
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 |
需求
常式 | 必要的標頭 |
---|---|
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
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應