命名空间
变体
操作

std::print(std::ostream)

来自 cppreference.cn
< 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,则等同于

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

目录

[编辑] 参数

os - 要插入数据的输出流
fmt - 表示格式化字符串的对象。格式化字符串由以下部分组成:
  • 普通字符(除了 {}),它们原样复制到输出,
  • 转义序列 {{}},它们在输出中分别替换为 {},以及
  • 替换字段。

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

{ arg-id (可选) } (1)
{ arg-id (可选) : format-spec } (2)
1) 没有格式化规范的替换字段
2) 带有格式化规范的替换字段
arg-id - 指定 args 中用于格式化的参数的索引;如果省略,则按顺序使用参数。

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

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

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

[编辑] 异常

[编辑] 注解

特性测试 标准 特性
__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.

[编辑] 参阅

输出带附加 '\n' 的参数格式化表示
(函数模板) [编辑]
(C++23)
使用参数的格式化表示打印到 stdout 或文件流
(函数模板) [编辑]
(C++20)
将参数的格式化表示存储在新字符串中
(函数模板) [编辑]