I have to format std::string with sprintf and send it into file stream. How can I do this?
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);