Skip to content

Instantly share code, notes, and snippets.

@t-mat
Created February 8, 2025 08:53
Show Gist options
  • Save t-mat/962d2daba1850fc2bb0dd94d3f9157b5 to your computer and use it in GitHub Desktop.
Save t-mat/962d2daba1850fc2bb0dd94d3f9157b5 to your computer and use it in GitHub Desktop.
[C++]vsprintf to std::vector<char>
#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