Created
January 29, 2012 22:53
-
-
Save dhoerl/1701181 to your computer and use it in GitHub Desktop.
std::string using printf style format strings
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
Prefer printf to the C++ iosstream methods? Now you can create a string using printf style format strings, and also append formatted string to existing strings. | |
Inspired by: http://stackoverflow.com/questions/2342162 |
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
std::string string_format(const char *fmt, ...) | |
{ | |
char *ret; | |
va_list ap; | |
va_start(ap, fmt); | |
vasprintf(&ret, fmt, ap); | |
va_end(ap); | |
std::string str(ret); | |
free(ret); | |
return str; | |
} | |
void append_format(std::string& str, const char *fmt, ...) | |
{ | |
va_list ap; | |
char *ret; | |
va_start(ap, fmt); | |
vasprintf(&ret, fmt, ap); | |
va_end(ap); | |
str.append(ret); | |
free(ret); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment