Created
October 5, 2021 16:15
-
-
Save stertingen/0d8c401f97cfead6c00866b8842f0c01 to your computer and use it in GitHub Desktop.
std::sprintf to std::string
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 <cerrno> | |
#include <cstring> | |
#include <iostream> | |
#include <string> | |
#include <utility> | |
template <typename... Args> | |
std::string strprintf(Args&&... args) { | |
std::string s; | |
const std::size_t sso = s.capacity(); | |
s.resize(sso); | |
const int res1 = std::snprintf(&s[0], sso, std::forward<Args>(args)...); | |
if (res1 < 0) return ""; | |
s.resize(res1); | |
if (static_cast<std::size_t>(res1) > sso) { | |
const int res2 = | |
std::snprintf(&s[0], s.size(), std::forward<Args>(args)...); | |
if (res2 != res1) return ""; | |
} | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment