std:: print (std::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... ) ) ; 。
如果对于
Args
中的任意
Ti
,
std::
formatter
<
Ti,
char
>
不满足
BasicFormatter
要求(根据
std::
make_format_args
的要求),则行为未定义。
目录 |
参数
| os | - | 用于插入数据的输出流 | ||||||||||||||||||||||||||||||||||||||||||||||
| fmt | - |
每个替换字段具有以下格式:
1)
不带格式说明的替换字段
2)
带格式说明的替换字段
|
||||||||||||||||||||||||||||||||||||||||||||||
| args... | - | 要格式化的参数 | ||||||||||||||||||||||||||||||||||||||||||||||
异常
- 分配失败时抛出 std::bad_alloc 。
- 传播任何由 formatter 抛出的异常(例如 std::format_error ),不关心 os. exceptions ( ) 的值,且不会在 os 的错误状态中设置 ios_base::badbit 。
- 可能抛出由 os. setstate ( ios_base :: badbit ) 引发的 ios_base::failure ,该调用在向 os 插入数据失败时执行。
注释
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__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)
|
将参数的格式化表示存储到新字符串中
(函数模板) |