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?
The main difference is that printf() is used to send formated string to the standard output, while cout doesn't let you do the same, if you are doing some program serious, you should be using printf().
Originally Answered: Why is it called printf rather print? The commonly accepted answer is that the 'f' at the end of the function name refers to “formatted”, indicating that the function requires a format string in addition to the values to be printed.
A printf function call with a single argument in general is not deprecated and has also no vulnerabilities when used properly as you always shall code.
puts() The function puts() is used to print the string on the output stream with the additional new line character '\n'. It moves the cursor to the next line. Implementation of puts() is easier than printf().
My students, who learn cin
and cout
first, then learn printf
later, overwhelmingly prefer printf
(or more usually fprintf
). I myself have found the printf
model sufficiently readable that I have ported it to other programming languages. So has Olivier Danvy, who has even made it type-safe.
Provided you have a compiler that is capable of type-checking calls to printf
, I see no reason not to use fprintf
and friends in C++.
Disclaimer: I am a terrible C++ programmer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With