std::print(std::ostream)
來自 cppreference.com
< cpp | io | basic_ostream
定義於標頭檔案 <ostream> |
||
template< class... Args > void print( std::ostream& os, std::format_string<Args...> fmt, Args&&... args ); |
(C++23 起) | |
根據格式字串 fmt 格式化 args,並將結果插入到 os 流中。
如果普通字面量編碼是 UTF-8,則等同於
- std::vprint_unicode(os, fmt.get(), std::make_format_args(args...));。否則為
- std::vprint_nonunicode(os, fmt.get(), std::make_format_args(args...));.
如果對於 `Args` 中的任何 `Ti`,std::formatter<Ti, char> 不滿足 BasicFormatter 要求(如 std::make_format_args 所要求),則行為未定義。
目錄 |
[編輯] 引數
os | - | 要插入資料的輸出流 | ||||||||||||||||||||||||||||||||||||||||||||||
fmt | - |
每個替換欄位具有以下格式:
1) 沒有格式化規範的替換欄位
2) 帶有格式化規範的替換欄位
| ||||||||||||||||||||||||||||||||||||||||||||||
args... | - | 要格式化的引數 |
[編輯] 異常
- 分配失敗時丟擲 std::bad_alloc。
- 傳播任何由任何 格式化器 丟擲的異常,例如 std::format_error,不考慮 os.exceptions() 的值,並且不將 ios_base::badbit 設定到 os 的錯誤狀態中。
- 如果向 os 插入失敗,則可能丟擲由 os.setstate(ios_base::badbit) 引起的 ios_base::failure。
[編輯] 註解
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_print |
202207L |
(C++23) | 格式化輸出 |
__cpp_lib_format |
202207L |
(C++23) | 公開 std::basic_format_string |
[編輯] 示例
執行此程式碼
#include <array> #include <cctype> #include <cstdio> #include <format> #include <numbers> #include <ranges> #include <sstream> int main() { std::array<char, 24> buf; std::format_to(buf.begin(), "{:.15f}", std::numbers::sqrt2); unsigned num{}, sum{}; for (auto n : buf | std::views::filter(isdigit) | std::views::transform([](char x) { return x - '0'; }) | std::views::take_while([&sum](char) { return sum < 42; })) sum += n, ++num; std::stringstream stream; #ifdef __cpp_lib_print std::print(stream, #else stream << std::format( #endif "√2 \N{ALMOST EQUAL TO} {0}.\n" "The sum of its first {1} digits is {2}.", std::numbers::sqrt2, num, sum ); std::puts(stream.str().data()); }
輸出
√2 ≈ 1.4142135623730951. The sum of its first 13 digits is 42.
[編輯] 參閱
(C++23) |
輸出帶附加 '\n' 的引數格式化表示 (函式模板) |
(C++23) |
使用引數的格式化表示列印到 stdout 或檔案流 (函式模板) |
(C++20) |
將引數的格式化表示儲存在新字串中 (函式模板) |