Skip to content

Instantly share code, notes, and snippets.

@6502
Last active October 23, 2016 20:35
Show Gist options
  • Save 6502/29327338e090789dde827577594b13ab to your computer and use it in GitHub Desktop.
Save 6502/29327338e090789dde827577594b13ab to your computer and use it in GitHub Desktop.
Reasonable string formatting for C++ (requires C++11)
#include <stdarg.c>
#include <string>
#include <vector>
std::string stringf(const char *fmt, ...) {
std::vector<char> buffer(256);
va_list args, cp;
va_start(args, fmt);
va_copy(cp, args);
int sz = vsnprintf(&buffer[0], buffer.size(), fmt, args);
if (sz >= int(buffer.size())) {
buffer.resize(sz + 1);
vsnprintf(&buffer[0], buffer.size(), fmt, cp);
}
va_end(cp);
va_end(args);
return &buffer[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment