I have to format std::string with sprintf and send it into file stream. How can I do this?
I realize this has been answered many times, but this is more concise:
std::string format(const std::string fmt_str, ...)
{
va_list ap;
char *fp = NULL;
va_start(ap, fmt_str);
vasprintf(&fp, fmt_str.c_str(), ap);
va_end(ap);
std::unique_ptr formatted(fp);
return std::string(formatted.get());
}
example:
#include
#include
int main()
{
std::random_device r;
std::cout << format("Hello %d!\n", r());
}
See also http://rextester.com/NJB14150