问题描述
我想知道什么是将字符串输出到带有变量的控制台的有效和聪明的方法。我知道在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";
如果您发现冗长和/或令人讨厌,请使用fmtlib作为std::format
的占位符。或与
#include <cstdio>
std::printf("The respondents of the survey were %d-%d years old.\n",a,b);
这不是类型安全的,但是当格式字符串保留文字时,最近的编译器会很擅长将您指向不匹配的格式说明符和参数。