我想知道什么是将字符串输出到带有变量的控制台的有效和聪明的方法。我知道在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);
那不是类型安全的,但是当格式字符串保留文字时,最近的编译器很擅长将您引向不匹配的格式说明符和参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句