Skip to content

Instantly share code, notes, and snippets.

@jniemann66
Last active January 7, 2026 00:02
Show Gist options
  • Select an option

  • Save jniemann66/ba3078eb95175c4a8495553e614b7d4d to your computer and use it in GitHub Desktop.

Select an option

Save jniemann66/ba3078eb95175c4a8495553e614b7d4d to your computer and use it in GitHub Desktop.
format a std::string with printf-style formatting
// utility function to do printf-style formatting on a std::string
#include <string>
template<typename ... Args>
static std::string format_string(const char* format, Args... args)
{
if (format) {
// get size from test run
const size_t sz = std::snprintf(nullptr, 0, format, args ...);
if(sz <= 0){
return {};
}
// make a buffer
std::vector<char> buf(sz + 1); // allow +1 for null terminator
// write to buffer, and construct std::string retval from it
std::snprintf(buf.data(), sz + 1, format, args...);
return std::string(buf.data(), sz);
}
return {};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment