Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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