std::string formatting like sprintf

前端 未结 30 2579
野趣味
野趣味 2020-11-22 04:42

I have to format std::string with sprintf and send it into file stream. How can I do this?

30条回答
  •  礼貌的吻别
    2020-11-22 05:29

    In order to format std::string in a 'sprintf' manner, call snprintf (arguments nullptr and 0) to get length of buffer needed. Write your function using C++11 variadic template like this:

    #include 
    #include 
    #include 
    
    template< typename... Args >
    std::string string_sprintf( const char* format, Args... args ) {
      int length = std::snprintf( nullptr, 0, format, args... );
      assert( length >= 0 );
    
      char* buf = new char[length + 1];
      std::snprintf( buf, length + 1, format, args... );
    
      std::string str( buf );
      delete[] buf;
      return str;
    }
    

    Compile with C++11 support, for example in GCC: g++ -std=c++11

    Usage:

      std::cout << string_sprintf("%g, %g\n", 1.23, 0.001);
    

提交回复
热议问题