std::print
来自 cppreference.cn
定义于头文件 <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> 不满足 BasicFormatter 对 Args
中任何 Ti
的要求(由 std::make_format_args 所要求),则行为未定义。
目录 |
[编辑] 参数
stream | - | 要写入的输出文件流 | ||||||||||||||||||||||||||||||||||||||||||||||
fmt | - |
每个替换字段具有以下格式
1) 没有格式说明符的替换字段
2) 带有格式说明符的替换字段
| ||||||||||||||||||||||||||||||||||||||||||||||
args... | - | 要格式化的参数 |
[编辑] 异常
- std::bad_alloc ,如果内存分配失败。
- std::system_error,如果写入流失败。
- 传播使用的 formatter 抛出的任何异常,例如 std::format_error。
[编辑] 注解
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
P3107R5 | C++23 | 只能执行缓冲打印操作 | 可以执行无缓冲打印操作 |
P3235R3 | C++23 | 添加的函数名称 由 P3107R5 引起误导 |
更改了函数名称 |
[编辑] 参见
(C++23) |
与 std::print 相同,除了每次打印都以额外的换行符结尾 (函数模板) |
(C++23) |
输出参数的格式化表示 (函数模板) |
(C++20) |
将参数的格式化表示存储在新字符串中 (函数模板) |
(C++20) |
通过输出迭代器写出其参数的格式化表示 (函数模板) |
(C++11) |
将格式化输出打印到 stdout、文件流或缓冲区 (函数) |