std::strtof, std::strtod, std::strtold
來自 cppreference.com
定義於標頭檔案 <cstdlib> |
||
float strtof ( const char* str, char** str_end ); |
(1) | (C++11 起) |
double strtod ( const char* str, char** str_end ); |
(2) | |
long double strtold( const char* str, char** str_end ); |
(3) | (C++11 起) |
解釋 str 指向的位元組字串中的浮點值。
函式會丟棄任何空白字元(由 std::isspace 確定),直到找到第一個非空白字元。然後,它儘可能多地獲取字元以形成有效的浮點表示,並將其轉換為浮點值。有效的浮點值可以是以下之一:
- 十進位制浮點表示式。它由以下部分組成:
- (可選) 加號或減號
- 非空十進位制數字序列,可選地包含小數點字元(由當前的 C 區域設定 確定)(定義有效數)
- (可選)
e
或E
,後跟可選的減號或加號以及非空十進位制數字序列(定義以 10 為底的指數)
|
(C++11 起) |
- 當前已安裝的 C 區域設定 可能接受的任何其他表示式。
函式會將 str_end 指向的指標設定為指向已解釋字元之後的字元。如果 str_end 是空指標,則忽略它。
目錄 |
[編輯] 引數
str | - | 指向要解釋的空終止位元組字串的指標 |
str_end | - | 指向字元指標的指標。 |
[編輯] 返回值
成功時返回與 str 內容對應的浮點值。如果轉換後的值超出相應返回型別的範圍,則發生範圍錯誤並返回 HUGE_VAL、HUGE_VALF 或 HUGE_VALL。如果無法執行轉換,則返回 0 並將 *str_end 設定為 str。
[編輯] 示例
執行此程式碼
#include <cerrno> #include <clocale> #include <cstdlib> #include <iostream> #include <string> int main() { const char* p = "111.11 -2.22 0X1.BC70A3D70A3D7P+6 -Inf 1.18973e+4932zzz"; char* end{}; std::cout << "Parsing \"" << p << "\":\n"; errno = 0; for (double f = std::strtod(p, &end); p != end; f = std::strtod(p, &end)) { std::cout << " '" << std::string(p, end - p) << "' -> "; p = end; if (errno == ERANGE) { std::cout << "range error, got "; errno = 0; } std::cout << f << '\n'; } if (std::setlocale(LC_NUMERIC, "de_DE.utf8")) { std::cout << "With de_DE.utf8 locale:\n"; std::cout << " '123.45' -> " << std::strtod("123.45", 0) << '\n'; std::cout << " '123,45' -> " << std::strtod("123,45", 0) << '\n'; } }
可能的輸出
Parsing "111.11 -2.22 0X1.BC70A3D70A3D7P+6 -Inf 1.18973e+4932zzz": '111.11' -> 111.11 ' -2.22' -> -2.22 ' 0X1.BC70A3D70A3D7P+6' -> 111.11 ' -Inf' -> -inf ' 1.18973e+4932' -> range error, got inf With de_DE.utf8 locale: '123.45' -> 123 '123,45' -> 123.45
[編輯] 參閱
將位元組字串轉換為浮點值 (函式) | |
將寬字串轉換為浮點值 (函式) | |
(C++17) |
將字元序列轉換為整數或浮點值 (函式) |
C 文件 關於 strtof, strtod, strtold
|