I've been looking through a lot of code made by others lately and happened to notice everyone uses "printf" style C functions a lot, but the C++ functions learned in school (cout, specifically) don't seem so popular.
Is this a valid observation, and is there a reason for this? Convention?
Thanks,
R
The only difference between sprintf() and printf() is that sprintf() writes data into a character array, while printf() writes data to stdout, the standard output device.
cout is a object for which << operator is overloaded, which send output to standard output device. 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().
Formatted I/O in C++ C++ helps you to format the I/O operations like determining the number of digits to be displayed after the decimal point, specifying number base etc. Note: Here, stream is referred to the streams defined in c++ like cin, cout, cerr, clog.
Answer: Yes. Printf can be used in C++. To use this function in a C++ program, we need to include the header <cstdio> in the program.
Personally, I use printf
over the iostream
stuff (like cout
) because I think it's clearer.
When you do formatting with iostream
, you have to <<
all sorts of weirdness like setiosflags
and setf
. I can never remember which namespace all this stuff lives in, let alone what it all does. Even when I do, I'm disappointed with how verbose and unintuitive the code looks.
The formatting options with printf
may seem illegible at first, but they're concise, clearly documented in a single manual page, and common to a wide range of languages.
Another advanage is that printf
is stateless: Unlike with cout
, I don't need to remember which member functions have been called on printf
, or which byzantine concoction of flags has been <<
'ed into it. This is a big plus for readability.
I think taste is one possible reason. Personally I find this:
printf("%8d: %s\n", customer->id, customer->name);
more readable than this:
std::cout << customer->id << ": " << customer->name << std::endl;
There's also the issue with localization. printf
makes it possible to change the formatting to suit other languages and UI cultures, which becomes a major chore with iostreams
, unless you use something like the Boost Format library.
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