Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the C formatted I/O functions (printf, sprintf, etc) more popular than IOStream, and if so, why? [closed]

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

like image 703
Russel Avatar asked Aug 29 '10 01:08

Russel


People also ask

What is the difference between printf () and sprintf () functions in C?

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.

Why do people use printf instead of cout?

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

What is formatted i/o Operation in C++?

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.

Can printf and scanf be used in C++?

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.


2 Answers

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.

like image 149
Andrew Cone Avatar answered Sep 26 '22 22:09

Andrew Cone


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.

like image 20
Mhmmd Avatar answered Sep 22 '22 22:09

Mhmmd