Created
August 18, 2020 20:42
-
-
Save charlie-x/d3b265ccb427139ee39619ae5736ebb9 to your computer and use it in GitHub Desktop.
std::format/vasprintf
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
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