I have to format std::string with sprintf and send it into file stream. How can I do this?
Based on the answer provided by Erik Aronesty:
std::string string_format(const std::string &fmt, ...) {
std::vector str(100,'\0');
va_list ap;
while (1) {
va_start(ap, fmt);
auto n = vsnprintf(str.data(), str.size(), fmt.c_str(), ap);
va_end(ap);
if ((n > -1) && (size_t(n) < str.size())) {
return str.data();
}
if (n > -1)
str.resize( n + 1 );
else
str.resize( str.size() * 2);
}
return str.data();
}
This avoids the need to cast away const
from the result of .c_str()
which was in the original answer.