Skip to content

Instantly share code, notes, and snippets.

@dhoerl
Created January 29, 2012 22:53
Show Gist options
  • Save dhoerl/1701181 to your computer and use it in GitHub Desktop.
Save dhoerl/1701181 to your computer and use it in GitHub Desktop.
std::string using printf style format strings
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
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