Skip to content

Instantly share code, notes, and snippets.

@smilingpoplar
Last active October 7, 2015 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smilingpoplar/3164359 to your computer and use it in GitHub Desktop.
Save smilingpoplar/3164359 to your computer and use it in GitHub Desktop.
string with format
string stringWithFormat(const char *fmt, ...) {
int desiredLength= 1024;
string str;
str.resize(desiredLength);
va_list ap;
while (true) {
va_start(ap, fmt);
int printedLength= vsnprintf((char *)str.c_str(), str.size()+1, fmt, ap);
va_end(ap);
// '-1' means the buffer was too small.
if (printedLength != -1 && size_t(printedLength) < str.size()) {
str.resize(printedLength);
break;
}
str.resize(2 * str.size() + 128);
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment