將字串轉換為單精確度浮點數值。
語法
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_VALF。 的 HUGE_VALF 正負號符合無法表示之值的正負號。 如果沒有任何轉換可執行,strtof 會傳回 0,否則會發生反向溢位。
wcstof 傳回類似 strtof 的值。 針對這兩個函式,errno如果發生溢位或下溢,而且叫用無效的參數處理程式,如參數驗證中所述, 會設定ERANGE為 。
如需傳回碼的詳細資訊,請參閱errno、 _doserrno_sys_errlist和 _sys_nerr。
備註
每個函式都會將輸入字串 strSource 轉換成 float。 strtof 函式會將 strSource 轉換成單精確度值。 strtof 停止在無法辨識為數位一部分的第一個字元讀取字串 strSource 。 此字元可能是終止的 Null 字元。 wcstof 是寬字元版本的 strtof,其 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 指向格式如下的字串︰
[] [signwhitespace] [] [digits.digits] [{e | E} [sign] digits]
whitespace 包含可忽略的空格及定位字元;sign 是加號 (+) 或減號 (-);而且 digits 是一或多個十進位數字。 如果基底字元前沒有任何數字,則在基底字元後至少必須要有一個數字。 小數位數的後面可以接著指數,包含簡介字母 (e 或 E) 以及選擇性帶正負號的整數。 如果沒有出現指數部分或基數位元,則會假設基數位元會遵循字串中的最後一個數位。 不符合此表單的第一個字元會停止掃描。
這些函式的 UCRT 版本不支援轉換 Fortran 樣式 (d 或 D) 指數字母。 舊版 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_l、 wcstod_wcstod_l
strtol、 、 wcstol、 _strtol_l_wcstol_l
strtoul、 、 _strtoul_l、 wcstoul_wcstoul_l
atof、 、 _atof_l、 _wtof_wtof_l
localeconv
_create_locale, _wcreate_locale
_free_locale