Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use printf in my C++ code?

Tags:

c++

formatting

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?

like image 791
Bob Dylan Avatar asked Jan 07 '10 00:01

Bob Dylan


People also ask

Should you use printf?

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().

Why printf is not used in C?

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.

Is printf outdated?

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.

What can I use instead of printf in C?

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().


1 Answers

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.

like image 160
Norman Ramsey Avatar answered Sep 26 '22 03:09

Norman Ramsey