I'm thinking about proposing the following as an alternative to sprintf/snprintf in our project.
The motivation is to remove the need to think about buffer sizes and keep as much of the convenience of the original as possible.
std::string strprintf(const char *format, ...)
{
std::string s;
s.resize(128); // best guess
char *buff = const_cast<char *>(s.data());
va_list arglist;
va_start(arglist, format);
auto len = vsnprintf(buff, 128, format, arglist);
va_end(arglist);
if (len > 127)
{
va_start(arglist, format);
s.resize(len + 1); // leave room for null terminator
buff = const_cast<char *>(s.data());
len = vsnprintf(buff, len+1, format, arglist);
va_end(arglist);
}
s.resize(len);
return s; // move semantics FTW
}
Does this code have any inherent problems?
usage example:
auto s = strprintf("Hello %d world", 777);