Created
February 8, 2025 08:53
-
-
Save t-mat/962d2daba1850fc2bb0dd94d3f9157b5 to your computer and use it in GitHub Desktop.
[C++]vsprintf to std::vector<char>
This file contains hidden or 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
#include <vector> // std::vector | |
#include <stdarg.h> // va_list, va_start, va_end, va_copy | |
size_t getVsprintfByteLength(const char *fmt, va_list vlist) { | |
va_list tmpVlist; | |
va_copy(tmpVlist, vlist); | |
size_t const byteLength = vsnprintf(nullptr, 0, fmt, tmpVlist); | |
va_end(tmpVlist); | |
return byteLength; | |
} | |
std::vector<char> vsprintfToVector(const char *fmt, va_list vlist) { | |
std::vector<char> buf(1 + getVsprintfByteLength(fmt, vlist)); | |
vsnprintf(buf.data(), buf.size(), fmt, vlist); | |
return buf; | |
} | |
std::vector<char> sprintfToVector(const char *fmt, ...) { | |
va_list vlist; | |
va_start(vlist, fmt); | |
std::vector<char> buf = vsprintfToVector(fmt, vlist); | |
va_end(vlist); | |
return buf; | |
} | |
int main() { | |
std::vector<char> const vec = sprintfToVector("%s, %s!", "Hello", "world"); | |
printf("%.*s\n", static_cast<unsigned>(vec.size()), vec.data()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment