7 ms·
Generally good advice, though I really don't agree about printf(). First, it certainly is possible to use objects with it; you may need a "%s" and a call to st
by makecheck 16y ago
Generally good advice, though I really don't agree about printf(). First, it certainly is possible to use objects with it; you may need a "%s" and a call to stringObject.c_str(), but it's no big deal.
There are many reasons to prefer printf() variants or other functions that use format strings, over the "standard" C++ stream mechanisms.
The main reason is that they're actually more convenient than stream classes in many cases. It is easier to see at a glance what the output will be, and it is a hell of a lot less kludgey to make certain things work. You also don't see stupid type problems like I did in a recent Linux port, where "object << std::string" had worked fine with one compiler and OS but not the other (an "object << C string pointer" definition was temporarily needed to bridge the gap).
C++ streams encourage code that constructs a lot of temporary objects; just look at the tricks required by standard-library implementations to get manipulators that take arguments, like "setw(int)", to even work! It is not impossible to avoid this, but programmers are not likely to, which makes it a bad paradigm.
Though not possible with printf() itself, format strings in general are more flexible than sequences of data. For instance, localization-aware code uses format strings because it's very important for another language to be able to say "%d %s" even if the English version uses the ordering "%s %d" (see for example CFStringCreateWithFormat() on Mac OS X, where substitutions can be placed arbitrarily). You also want to be able to swap in an entire translated string, and not have to piece together tidbits that are in between "<<" operators.
About the only defensible use of streams is for files, because by default they support RAII and make it a little easier to automatically clean up. Of course, it takes 2 minutes to write a wrapper class that does the same thing for any other kind of file representation, and then you have exception safety anyway.