Why iostream and not stdio?

xtknight

Elite Member
Oct 15, 2004
12,974
0
71
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.)
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
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.
 

duragezic

Lifer
Oct 11, 1999
11,234
4
81
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.
 

BFG10K

Lifer
Aug 14, 2000
22,709
3,007
126
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.
 

Matthias99

Diamond Member
Oct 7, 2003
8,808
0
0
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.