如何在 C++ 17 中使用变量正确格式化输出字符串?

How does one correctly format a string on output with variables in C++ 17?

我想知道将字符串输出到带有变量的控制台的有效且智能的方法是什么。我知道在 C++20 中有 std::format 这使得这很容易,但我不确定 C++17。

例如,可以在 C++20 中完成:

#include <iostream>
#include <string>
#inclide <format>

int main(){

    int a = 13;
    int b = 50;
    std::string out_str = std::format("The respondents of the survey were {}-{} years old.", a, b);

    std::cout << out_str << std::endl;

    return EXIT_SUCCESS;

}

有没有类似于上面 C++17 中示例的好方法?.. 或者我只需要将字符串和变量的不同部分分开?

std::cout << "The respondents of the survey were " << a << "-" << b
   << " years old\n";

如果您觉得冗长的 and/or 很烦人,请使用 fmtlib 作为 std::format 的占位符。或者去 old-school 和

#include <cstdio>

std::printf("The respondents of the survey were %d-%d years old.\n", a, b);

那不是 type-safe,但是当格式字符串保持文字时,最近的编译器非常擅长将您指向 non-matching 格式说明符和参数。