Skip to content

Instantly share code, notes, and snippets.

@charlie-x
Created August 18, 2020 20:42
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 charlie-x/d3b265ccb427139ee39619ae5736ebb9 to your computer and use it in GitHub Desktop.
Save charlie-x/d3b265ccb427139ee39619ae5736ebb9 to your computer and use it in GitHub Desktop.
std::format/vasprintf
int vasprintf(char** strp, const char* format, va_list ap)
{
int len = _vscprintf(format, ap);
if (len == -1)
return -1;
char* str = (char*)malloc((size_t)len + 1);
if (!str)
return -1;
int retval = vsnprintf(str, len + 1, format, ap);
if (retval == -1) {
free(str);
return -1;
}
*strp = str;
return retval;
}
std::string format(const std::string fmt_str, ...)
{
va_list ap;
char* fp = NULL;
va_start(ap, fmt_str);
vasprintf(&fp, fmt_str.c_str(), ap);
va_end(ap);
std::unique_ptr<char[]> formatted(fp);
return std::string(formatted.get());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment