Is it possible to format std::string
passing a set of arguments?
Currently I am formatting the string this way:
string helloString = \"Hello
You can do it with the Boost.Format library, because you can feed the arguments one by one.
This actually enables you to achieve your goal, quite unlike the printf
family where you have to pass all the arguments at once (i.e you'll need to manually access each item in the container).
Example:
#include
#include
#include
#include
std::string format_range(const std::string& format_string, const std::vector& args)
{
boost::format f(format_string);
for (std::vector::const_iterator it = args.begin(); it != args.end(); ++it) {
f % *it;
}
return f.str();
}
int main()
{
std::string helloString = "Hello %s and %s";
std::vector args;
args.push_back("Alice");
args.push_back("Bob");
std::cout << format_range(helloString, args) << '\n';
}
You can work from here, make it templated etc.
Note that it throws exceptions (consult documentation) if the vector doesn't contain the exact amount of arguments. You'll need to decide how to handle those.