std::print(std::ostream)
来自cppreference.com
| 在标头 <ostream> 定义
|
||
| |
(C++23 起) | |
根据格式字符串 fmt 格式化 args,将结果插入流 os。
如果通常字面量编码是 UTF-8,则上式等价于:
- std::vprint_unicode
(os, fmt.get(), std::make_format_args(args...));。 - 否则等价于 std::vprint_nonunicode
(os, fmt.get(), std::make_format_args(args...));。
若 Args 中有任何 Ti,其 std::formatter<Ti, char> 不满足基本格式化器 (BasicFormatter) ,则其行为未定义(正如 std::make_format_args 所要求的)。
参数
| os | - | 要插入数据的输出流 | |||||||||||||||||||
| fmt | - |
每个替换域拥有如下格式:
1) 没有格式说明的替换域
2) 有格式说明的替换域
| |||||||||||||||||||
| args... | - | 参与格式化的实参 |
异常
- 内存分配失败时抛出 std::bad_alloc。
- 传播由其所使用的格式化器所抛出的任何异常,比如 std::format_error,不管
os.exceptions()的值如何,也不会在os的错误状态中打开 std::ios_base::badbit。 - 向
os的插入失败时,可能会抛出由os.setstate(ios_base::badbit)调用所造成的 std::ios_base::failure。
注解
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_print |
202207L |
(C++23) | 格式化输出 |
__cpp_lib_format |
202207L |
(C++23) | 暴露 std::basic_format_string |
示例
Run this code
#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"
"其前 {1} 位的和是 {2}。",
std::numbers::sqrt2, num, sum
);
std::puts(stream.str().data());
}
输出:
√2 ≈ 1.4142135623730951。
其前 13 位的和是 42。
参阅
(C++23) |
输出各实参的格式化表示并追加 '\n' (函数模板) |
(C++23) |
将参数的格式化表达输出到 stdout 或文件缓冲区 (函数模板) |
(C++20) |
在新字符串中存储参数的格式化表示 (函数模板) |