Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to safely printf to a string? [duplicate]

Tags:

c++

stl

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?

like image 928
user48956 Avatar asked Jan 12 '09 18:01

user48956


People also ask

How can I make printf print instantly?

The output stream stdout is buffered by default, so if you want immediate output you'll need to flush the output stream - using fflush - or cause a newline to be printed in the printf : printf("Starting nets allocation..."); fflush(stdout); Or: printf("Starting nets allocation...

Does printf print until null terminator?

C strings are null-terminated by convention. That means that printf , or any other function receiving a C string, will read the pointed memory till it encounters a null character. In your case there's no null terminator in str , so printf will keep reading from whatever memory comes next.

How do I printf a string?

We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.

Can you multiply printf in C?

No, you can't do this in 'C' as far as I think.In python multiplication of a string by a number is defined as 'repetition' of the string that number of times. One way you can do this in 'C++'(a superset of 'C' language) is through 'operator overloading'.


1 Answers

You can use:

std::snprintf if you are working with a char*

std::stringstream if you want to use strings (not same as printf but will allow you to easily manipulate the string using the normal stream functions).

boost::format if you want a function similar to printf that will work with streams. (as per jalf in comments)

fmt::format which is has been standardized since c++20 std::format

like image 84
6 revs, 4 users 65% Avatar answered Oct 05 '22 12:10

6 revs, 4 users 65%