Possible Duplicates:
printf vs cout in C++ cin or printf??
I've开发者_Python百科 always wondered about printf and cout.. which one is ultimately faster, and is it the most flexible as well (ie can print a range of variables, and output can be formatted)?
P.S. I know this looks similar to 'printf' vs. 'cout' in C++ ,but i'm not really asking the same thing.
Short Answer
Faster : printf
More flexible : cout
Long answer
When compared to the sprintf family, the C++ streams are supposed to be slower (by a factor 6 if I recall an item of Exceptional C++, by Herb Sutter). Still, most of the time, you won't need this speed, but you need to be sure your code won't be bugged.
And it is easy to do something wrong with the printf family of functions, be it putting the wrong number of arguments, the wrong types, or even introduce potential security vulnerability (the %n specifier comes to mind) in your code.
Unless really wanting it (and then, it's called sabotage), it's almost impossible to get it wrong with C++ streams. They handle seamlessly all known types (build-ins, std::strings, etc.), and it's easy to extend it. For example, let's say I have an object "Coordinate3D", and that I want to print out its data:
#include <iostream>
struct Coordinate3D
{
int x ;
int y ;
int z ;
} ;
std::ostream & operator << (std::ostream & p_stream
, const Coordinate3D & p_c)
{
return p_stream << "{ x : " << p_c.x
<< " , y : " << p_c.y
<< " , z : " << p_c.z << " }" ;
}
int main(int argc, char * argv[])
{
Coordinate3D A = {25,42,77} ;
std::cout << A << std::endl ;
// will print "{ x : 25 , y : 42 , z : 77 }"
return 0 ;
}
The problem with the stream is that they are quite difficult to handle correctly when wanting to specify format of some data (padding spaces for numbers, for example), and that sometimes, you really really need to go fast. Then, either fall back to printf, or try some high-speed C++ alternatives (FastFormat comes to mind).
Edit: Note that Thomas' series of tests show interesting results (which I reproduced right now on my computer), that is: cout
and printf
have similar performances when one avoids using std::endl
(which flushes the output in addition to outputing a \n
).
- Faster: printf
- More typesafe and extensible: cout
- Better: depends! I like
printf
more.
I'm not alone in thinking that the way C++'s cout does formatting is just epic fail.
精彩评论