std:: print
|
定义于头文件
<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 ,并将结果输出到输出流。
? 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_nonunicode ( stream, fmt. str , std:: make_format_args ( args... ) )
: std :: vprint_nonunicode_buffered ( stream, fmt. str , std:: make_format_args ( args... ) ) ; .
如果对于
Args
中的任意
Ti
,
std::
formatter
<
Ti,
char
>
不满足
BasicFormatter
要求(根据
std::make_format_args
的要求),则行为未定义。
目录 |
参数
| 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"); // 重载 (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()); // 重载 (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
、文件流或缓冲区
(函数) |