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,则等价于
- std::vprint_unicode(os, fmt.get(), std::make_format_args(args...));. 否则,
- std::vprint_nonunicode(os, fmt.get(), std::make_format_args(args...));.
如果 std::formatter
目录 |
[编辑] 参数
os | - | 要将数据插入的输出流 | ||||||||||||||||||||||||||||||||||||||||||||||
fmt | - |
每个替换字段具有以下格式
1) 没有格式规范的替换字段
2) 具有格式规范的替换字段
| ||||||||||||||||||||||||||||||||||||||||||||||
args... | - | 要格式化的参数 |
[编辑] 异常
- std::bad_alloc,在分配失败时抛出。
- 传播任何 formatter 抛出的异常,例如 std::format_error,不考虑 os.exceptions() 的值,也不在 os 的错误状态中打开 ios_base::badbit。
- 如果插入 os 失败,可能会抛出由 os.setstate(ios_base::badbit) 引起的 ios_base::failure。
[编辑] 注释
特性测试宏 | 值 | Std | 特性 |
---|---|---|---|
__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.
[编辑] 参见
(C++23) |
输出带有附加 '\n' 的参数的格式化表示 (函数模板) |
(C++23) |
使用参数的格式化表示打印到 stdout 或文件流 (函数模板) |
(C++20) |
将参数的格式化表示存储在新字符串中 (函数模板) |