strtof, strtod, strtold
來自 cppreference.com
在標頭檔案 <stdlib.h> 中定義 |
||
float strtof ( const char* restrict str, char** restrict str_end ); |
(1) | (C99 起) |
(2) | ||
double strtod ( const char* str, char** str_end ); |
(直到 C99) | |
double strtod ( const char* restrict str, char** restrict str_end ); |
(C99 起) | |
long double strtold( const char* restrict str, char** restrict str_end ); |
(3) | (C99 起) |
將 str 指向的位元組字串解釋為浮點值。
函式會丟棄任何空白字元(由 isspace 確定),直到找到第一個非空白字元。然後,它會盡可能多地獲取字元以形成一個有效的浮點表示,並將它們轉換為一個浮點值。有效的浮點值可以是以下之一:
- 十進位制浮點表示式。它由以下部分組成:
- (可選) 加號或減號
- 非空十進位制數字序列,可選地包含小數點字元(由當前的 C locale 確定)(定義有效數字)
- (可選)
e
或E
,後跟可選的減號或加號以及非空十進位制數字序列(定義以 10 為底的指數)
|
(C99 起) |
- 當前安裝的 C locale 可能接受的任何其他表示式。
函式會將 str_end 指向的指標設定為指向最後一個被解釋字元的下一個字元。如果 str_end 是空指標,則忽略它。
目錄 |
[編輯] 引數
str | - | 指向要解釋的空終止位元組字串的指標 |
str_end | - | 指向字元指標的指標 |
[編輯] 返回值
成功時,返回對應於 str 內容的浮點值。如果轉換後的值超出相應返回型別的範圍,則發生範圍錯誤(errno 設定為 ERANGE),並返回 HUGE_VAL、HUGE_VALF 或 HUGE_VALL。如果無法執行轉換,則返回 0。
[編輯] 示例
執行此程式碼
#include <errno.h> #include <stdio.h> #include <stdlib.h> int main(void) { // parsing with error handling const char* p = "111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz"; printf("Parsing '%s':\n", p); char* end = NULL; for (double f = strtod(p, &end); p != end; f = strtod(p, &end)) { printf("'%.*s' -> ", (int)(end - p), p); p = end; if (errno == ERANGE) { printf("range error, got "); errno = 0; } printf("%f\n", f); } // parsing without error handling printf("\" -0.0000000123junk\" --> %g\n", strtod(" -0.0000000123junk", NULL)); printf("\"junk\" --> %g\n", strtod("junk", NULL)); }
可能的輸出
Parsing '111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz': '111.11' -> 111.110000 ' -2.22' -> -2.220000 ' Nan' -> nan ' nan(2)' -> nan ' inF' -> inf ' 0X1.BC70A3D70A3D7P+6' -> 111.110000 ' 1.18973e+4932' -> range error, got inf " -0.0000000123junk" --> -1.23e-08 "junk" --> 0
[編輯] 參考
- C23 標準 (ISO/IEC 9899:2024)
- 7.22.1.3 strtod、strtof 和 strtold 函式 (p: TBD)
- C17 標準 (ISO/IEC 9899:2018)
- 7.22.1.3 strtod、strtof 和 strtold 函式 (p: 249-251)
- C11 標準 (ISO/IEC 9899:2011)
- 7.22.1.3 strtod、strtof 和 strtold 函式 (p: 342-344)
- C99 標準 (ISO/IEC 9899:1999)
- 7.20.1.3 strtod、strtof 和 strtold 函式 (p: 308-310)
- C89/C90 標準 (ISO/IEC 9899:1990)
- 4.10.1.4 strtod 函式
[編輯] 另請參閱
將位元組字串轉換為浮點值 (函式) | |
(C99)(C95)(C99) |
將寬字串轉換為浮點值 (函式) |
C++ 文件 用於 strtof, strtod, strtold
|