c++中的format()函数

在c++20中新增了std::format()函数,记录一下使用,顺便一提,format内部是支持格式化的,详见参考手册。


C++参考手册

https://zh.cppreference.com/w/cpp/utility/format/format

官方示例

#include <format>
#include <iostream>
#include <string>
#include <string_view>
 
template <typename... Args>
std::string dyna_print(std::string_view rt_fmt_str, Args&&... args) {
    return std::vformat(rt_fmt_str, std::make_format_args(args...));
}
 
int main() {
    std::cout << std::format("Hello {}!\n", "world");
 
    std::string fmt;
    for (int i{}; i != 3; ++i) {
        fmt += "{} "; // 构造格式化字符串
        std::cout << fmt << " : ";
        std::cout << dyna_print(fmt, "alpha", 'Z', 3.14, "unused");
        std::cout << '\n';
    }
}

输出

Hello world!
{}  : alpha 
{} {}  : alpha Z 
{} {} {}  : alpha Z 3.14
posted @ 2023-01-05 17:23  德图没有脑子!  阅读(1398)  评论(0)    收藏  举报