std::print
來自 cppreference.com
定義於標頭檔案 <print> |
||
template< class... Args > void print( std::format_string<Args...> fmt, Args&&... args ); |
(1) | (C++23 起) |
template< class... Args > void print( std::FILE* stream, |
(2) | (C++23 起) |
根據格式化字串 fmt 格式化 args,並將結果列印到輸出流。
1) 等價於 std::print(stdout, fmt, std::forward<Args>(args)...)。
2) 如果普通字面量編碼是 UTF-8,則等價於 (std::enable_nonlocking_formatter_optimization<std::remove_cvref_t<Args>> && ...)
? std::vprint_unicode(stream, fmt.str, std::make_format_args(args...))
: std::vprint_unicode_buffered(stream, fmt.str, std::make_format_args(args...));。
? std::vprint_unicode(stream, fmt.str, std::make_format_args(args...))
: std::vprint_unicode_buffered(stream, fmt.str, std::make_format_args(args...));。
否則,等價於 (std::enable_nonlocking_formatter_optimization<std::remove_cvref_t<Args>> && ...)
? std::vprint_nonunicode(stream, fmt.str, std::make_format_args(args...))
: std::vprint_nonunicode_buffered(stream, fmt.str, std::make_format_args(args...));。
? std::vprint_nonunicode(stream, fmt.str, std::make_format_args(args...))
: std::vprint_nonunicode_buffered(stream, fmt.str, std::make_format_args(args...));。
如果 std::formatter<Ti, char> 不滿足 std::make_format_args 所要求的任何 Args
中的 Ti
的 BasicFormatter 要求,則行為未定義。
目錄 |
[編輯] 引數
stream | - | 要寫入的輸出檔案流 | ||||||||||||||||||||||||||||||||||||||||||||||
fmt | - |
每個替換欄位具有以下格式:
1) 沒有格式化規範的替換欄位
2) 帶有格式化規範的替換欄位
| ||||||||||||||||||||||||||||||||||||||||||||||
args... | - | 要格式化的引數 |
[編輯] 異常
- 分配失敗時丟擲 std::bad_alloc。
- 如果寫入流失敗,丟擲 std::system_error。
- 傳播使用的 格式化器 丟擲的任何異常,例如 std::format_error。
[編輯] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_print |
202207L |
(C++23) | 格式化輸出 |
202403L |
(C++26) (DR23) |
無緩衝格式化輸出 | |
202406L |
(C++26) (DR23) |
為更多可格式化型別啟用無緩衝格式化輸出 | |
__cpp_lib_format |
202207L |
(C++23) | 公開 std::basic_format_string |
[編輯] 示例
執行此程式碼
#include <cstdio> #include <filesystem> #include <print> int main() { std::print("{2} {1}{0}!\n", 23, "C++", "Hello"); // overload (1) const auto tmp{std::filesystem::temp_directory_path() / "test.txt"}; if (std::FILE* stream{std::fopen(tmp.c_str(), "w")}) { std::print(stream, "File: {}", tmp.string()); // overload (2) std::fclose(stream); } }
輸出
Hello C++23!
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
P3107R5 | C++23 | 只能執行緩衝列印操作 | 可以執行無緩衝列印操作 |
P3235R3 | C++23 | 新增的函式名稱 P3107R5 具有誤導性 |
更改了函式名稱 |
[編輯] 另請參閱
(C++23) |
與 std::print 相同,但每次列印都以額外的換行符終止 (函式模板) |
(C++23) |
輸出引數的格式化表示 (函式模板) |
(C++20) |
將引數的格式化表示儲存在新字串中 (函式模板) |
(C++20) |
透過輸出迭代器寫出其引數的格式化表示 (函式模板) |
(C++11) |
將格式化輸出列印到 stdout、檔案流或緩衝區 (函式) |