• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Why iostream and not stdio?

xtknight

Elite Member
I am curious as to why people eschew printf/sprintf in favor of cout, ios::, etc. Printf is probably the best function in all of the libraries as it offers so much flexibility and power with so little code. For example, if I wanted to put the current time in the format "00:00:00" (hh:mm:ss):

time_t curr;
tm local;
time(&curr);
local=*(localtime(&curr)); // dereference and assign

With cout

cout.width(2); cout.fill('0');
cout << local.tm_hour << ":";
cout.width(2); cout.fill('0');
cout << local.tm_min << ":";
cout.width(2); cout.fill('0');
cout << local.tm_sec << " ";
cout.width(0);

Why all that work when you can just do

With printf

printf("%02d:%02d:%02d", local.tm_hour, local.tm_min, local.tm_sec);

(Yes, I have seen several examples of people doing it the hard way.)
 
I would assume mostly because printf is part of the standard C library and iostream is part of the standard C++ libraries. A lot of people really hate reading through code that's a mix of the two.
 
I've mostly used iostream, since my C++ class I've had this semester only touched on C for a few days. But differences we learned was that iostream was type safe, object-oriented, and could make use of C++ features like operator overloading. Overloading << or >> is pretty handy for easily printing user made objects. Though your example is a good one why printf can be more useful.
 
Yeah, type safing is a big reason. Specifically if you pass the wrong type parameters to printf it can make very difficult bugs to track down.
 
Trying to work with functions that have variable numbers of arguments makes me want to either cry or puke. 🙁

It's *much* easier to overload and write wrappers around the iostream stuff than printf(). For instance, you can have a function that takes a pointer to an arbitrary iostream and then prints to that. fprintf() sort of does this, but can only print to a (FILE*).

I will admit that I have, at times, used sprintf() to write a formatted string and then outputted it using an iostream. When you want really complex formatting, it's usually easier to understand the printf() formatting string than dozens of cout commands.
 
Back
Top