printf vs. std::cout

aali picture aali · Jan 24, 2011 · Viewed 30.3k times · Source

Possible Duplicate:
Should I use printf in my C++ code?

If I just want to print a string on screen, I can do that using those two ways:

printf("abc");

std::cout << "abc" << std::endl;

The case is, and in the examples shown above, is there an advantage of using printf over std::cout, or, vice versa?

Answer

dandan78 picture dandan78 · Jan 24, 2011

While cout is the proper C++ way, I believe that some people and companies (including Google) continue to use printf in C++ code because it is much easier to do formatted output with printf than with cout.

Here's an interesting example that I found here.

Compare:

printf( "%-20s %-20s %5s\n" , "Name" , "Surname" , "Id" );

and

cout << setw( -20 ) << "Name" << setw( 20 ) << "Surname"  << setw( 5 ) << "Id" << endl;