Last active
October 7, 2015 12:18
-
-
Save smilingpoplar/3164359 to your computer and use it in GitHub Desktop.
string with format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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