Namespaces
Variants

std:: print

From cppreference.net
< cpp ‎ | io
定义于头文件 <print>
template < class ... Args >
void print ( std:: format_string < Args... > fmt, Args && ... args ) ;
(1) (C++23 起)
template < class ... Args >

void print ( std:: FILE * stream,

std:: format_string < Args... > fmt, Args && ... args ) ;
(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 :: 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... ) ) ;
.

如果对于 Args 中的任意 Ti std:: formatter < Ti, char > 不满足 BasicFormatter 要求(根据 std::make_format_args 的要求),则行为未定义。

目录

参数

stream - 用于写入的输出文件流
fmt - 表示格式字符串的对象。格式字符串包含:
  • 普通字符(除了 { } ),它们会原样复制到输出中,
  • 转义序列 { { } } ,它们在输出中分别被替换为 { } ,以及
  • 替换字段。

每个替换字段具有以下格式:

{ arg-id (optional) } (1)
{ arg-id (optional) : format-spec } (2)
1) 不带格式说明的替换字段
2) 带格式说明的替换字段
arg-id - 指定 args 中参数的索引,其值将用于格式化;如果省略,则按顺序使用参数。

格式字符串中的 arg-id 必须全部存在或全部省略。混合手动和自动索引是错误的。

format-spec - 由对应参数的 std::formatter 特化定义的格式规范。不能以 } 开头。

(since C++23)
(since C++26)
  • 对于其他可格式化类型,格式规范由用户定义的 formatter 特化决定。
args... - 要格式化的参数

异常

注释

功能测试 标准 功能
__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++20)
将参数的格式化表示存储到新字符串中
(函数模板)
(C++20)
通过输出迭代器写入参数的格式化表示
(函数模板)
将格式化输出打印到 stdout 、文件流或缓冲区
(函数)