Last active
January 7, 2026 00:02
-
-
Save jniemann66/ba3078eb95175c4a8495553e614b7d4d to your computer and use it in GitHub Desktop.
format a std::string with printf-style formatting
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
| // 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