Skip to content

Instantly share code, notes, and snippets.

@stertingen
Created October 5, 2021 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stertingen/0d8c401f97cfead6c00866b8842f0c01 to your computer and use it in GitHub Desktop.
Save stertingen/0d8c401f97cfead6c00866b8842f0c01 to your computer and use it in GitHub Desktop.
std::sprintf to std::string
#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