I'm wondering what is the efficient and smart way to output a string to console with variables. I know in C++20 there is std::format which makes this easy, but I'm unsure about C++17.
For example, as it could be done in 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;
}
Is there a nice way to do it akin to the example above in C++17?.. Or do I simply have to separate out different parts of the string and variables?
format
doesn't let you do that. C++ isn't Python, so you shouldn't expect it to do what Python does. – Stallfeeda
andb
. It can do Printf-style formatting, where you would have"{}-{}"
in the string, and you passa
andb
to the format function. Butformat
can't finda
andb
on its own. – Stallfeed