【问题标题】:How do I print to stdout or a file using C++20 std::format如何使用 C++20 std::format 打印到标准输出或文件
【发布时间】:2022-08-15 13:53:27
【问题描述】:

众所周知,没有进入 C++20 的 std::format 的一件事是打印到标准输出或通用文件流的函数。我们已经承诺在 C++23 中使用 std::print() 来满足这一需求,但这并不能暂时解决问题。

有哪些选择可以解决这个问题?

  • 只需out << std::format(...),因为std::format 返回一个字符串

标签: format c++20 cout


【解决方案1】:

回答我自己的问题,解决方案其实很简单。 std::format_to 可以写入输出迭代器,因此只需要构造一个合适的迭代器即可。

#include <iostream>
#include <iterator>
#include <format>

int main()
{
    std::ostream_iterator<char> out(std::cout);  // Create an output iterator that writes to std::cout
                                                 // Replace std::cout with an ostream to write to a file
    std::format_to(out, "Hello {}!\n", "world");
    return 0;
}

【讨论】:

    猜你喜欢
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 2014-07-22
    • 2011-01-08
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多