fork(60) download
  1. #include <memory>
  2. #include <string>
  3. #include <stdexcept>
  4.  
  5. template<typename ... Args>
  6. std::string string_format( const std::string& format, Args ... args )
  7. {
  8. size_t size = snprintf( nullptr, 0, format.c_str(), args ... ) + 1; // Extra space for '\0'
  9. if( size <= 0 ){ throw std::runtime_error( "Error during formatting." ); }
  10. std::unique_ptr<char[]> buf( new char[ size ] );
  11. snprintf( buf.get(), size, format.c_str(), args ... );
  12. return std::string( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside
  13. }
  14.  
  15.  
  16. // Testing
  17. #include <iostream>
  18.  
  19. int main() {
  20. //test the function here
  21. std::cout << string_format("%d", 202412);
  22. //<test>
  23. return 0;
  24. }
Success #stdin #stdout 0s 4536KB
stdin
Standard input is empty
stdout
202412