Should I use printf in my C++ code?

2019-01-10 08:07发布

I generally use cout and cerr to write text to the console. However sometimes I find it easier to use the good old printf statement. I use it when I need to format the output.

One example of where I would use this is:

// Lets assume that I'm printing coordinates... 
printf("(%d,%d)\n", x, y);

// To do the same thing as above using cout....
cout << "(" << x << "," << y << ")" << endl;

I know I can format output using cout but I already know how to use the printf. Is there any reason I shouldn't use the printf statement?

19条回答
霸刀☆藐视天下
2楼-- · 2019-01-10 08:48

Even though the question is rather old, I want to add my two cents.

Printing user-created objects with printf()

This is rather simple if you think about it - you can stringify your type and sent the string to printf:

std::string to_string(const MyClass &x)
{
     return to_string(x.first)+" "+to_string(x.second);
}

//...

printf("%s is awesome", to_string(my_object).c_str()); //more or less

A shame there wasn't (there is C++11 to_string()) standarized C++ interface to stringify objects...

printf() pitfall

A single flag - %n

The only one that is an output parameter - it expects pointer to int. It writes number of succesfully written characters to location pointed by this pointer. Skillful use of it can trigger overrun, which is security vulnerability (see printf() format string attack).

查看更多
登录 后发表回答