Skip to content

Instantly share code, notes, and snippets.

@aont
Created February 17, 2012 05:38
Show Gist options
  • Select an option

  • Save aont/1850964 to your computer and use it in GitHub Desktop.

Select an option

Save aont/1850964 to your computer and use it in GitHub Desktop.
sprintf returning std::string
/* from http://www.ohfuji.name/?p=4 */
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <vector>
#include <string>
#include <stdexcept>
std::string str_printf(const char* const format, ...)
{
int bufsize = 1024;
std::vector<char> buff(bufsize);
va_list args;
/// first try
va_start(args, format);
int vssize = vsnprintf( &buff[0], bufsize, format, args);
va_end(args);
/// if bufsize is sufficient, return
if(vssize>=0 && vssize<bufsize) {
buff.resize(vssize);
return std::string(buff.begin(), buff.end());
}
if(vssize<0) throw std::runtime_error(format);
/// resize and retry
buff.resize(vssize + 1);
va_start(args, format);
vssize = vsnprintf(&buff[0], vssize + 1, format, args);
va_end(args);
if(vssize<0) throw std::runtime_error(format);
buff.resize(vssize);
return std::string(buff.begin(), buff.end());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment