fork download
  1. #include <string>
  2. #include <memory>
  3. #include <cstring>
  4. #include <cstdarg>
  5. #include <cstdio>
  6.  
  7. static std::string string_format(const std::string fmt_str, ...)
  8. {
  9. int final_n, n = ((int)fmt_str.size()) * 2; /* Reserve two times as much as the length of the fmt_str */
  10. std::unique_ptr<char[]> formatted;
  11. va_list ap;
  12. while(1) {
  13. formatted.reset(new char[n]); /* Wrap the plain char array into the unique_ptr */
  14. std::strcpy(&formatted[0], fmt_str.c_str());
  15. va_start(ap, fmt_str);
  16. final_n = vsnprintf(&formatted[0], n, fmt_str.c_str(), ap);
  17. va_end(ap);
  18. if (final_n < 0 || final_n >= n)
  19. n += std::abs(final_n - n + 1);
  20. else
  21. break;
  22. }
  23. return std::string(formatted.get());
  24. }
  25.  
  26. int main()
  27. {
  28. puts(string_format("%s %d", "test", 1).c_str());
  29. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
test 1