Is it possible to format std::string
passing a set of arguments?
Currently I am formatting the string this way:
string helloString = \"Hello
The most C++-ish way to achieve sprintf-like functionality would be to use stringstreams.
Here is an example based on your code:
#include
// ...
std::stringstream ss;
std::vector tokens;
ss << "Hello " << tokens.at(0) << " and " << tokens.at(1);
std::cout << ss.str() << std::endl;
Pretty handy, isn't it ?
Of course, you get the full benefit of IOStream manipulation to replace the various sprintf flags, see here http://www.fredosaurus.com/notes-cpp/io/omanipulators.html for reference.
A more complete example:
#include
#include
#include
#include
int main() {
std::stringstream s;
s << "coucou " << std::setw(12) << 21 << " test";
std::cout << s.str() << std::endl;
return 0;
}
which prints:
coucou 21 test
Edit:
As pointed by the OP, this way of doing things does not allow for variadic arguments, because there is no `template' string built beforehand allowing the stream to iterate over the vector and insert data according to placeholders.