Search code examples
c++stl

Best way to safely printf to a string?


Does anyone know a good safe way to redirect the output of a printf-style function to a string? The obvious ways result in buffer overflows.

Something like:

string s;
output.beginRedirect( s );  // redirect output to s

... output.print( "%s%d", foo, bar );

output.endRedirect();

I think the problem is the same as asking, "how many characters will print produce?" Ideas?


Solution

  • This StackOverflow question has a similar discussion. Also in that question I present my favorite solution, a "format" function that takes identical arguments to printf and returns a std::string.