cout and printf [duplicate]
Possible Duplicate:
printf vs 开发者_如何学运维cout in C++
What are the differences between cout and printf?
cout automatically make casts and finds out the type of the variables you are trying to print. So you can do something like:
int myint = 5;
cout << myint;
And cout will detect that myint is an int and print it. With printf, you have to specify what is the type of the variable you are trying to print:
int myint = 5;
printf("%d", myint);
Also, cout is slower than printf (because it does the type detection...), although in most practical applications, you won't notice the performance difference.
printf
is the function used for printing data on the standard output of the stdio
library, the IO library of C. It's kept in C++ mainly for legacy reasons, although sometimes it's still useful.
cout
is a C++ stream from the iostreams library (in particular, it's defined to be a ostream &
); the iostreams library is the native C++ way to perform IO.
In general it's easier and safer to use iostreams than the old printf-like functions (thanks to <<
operator overloading instead of format strings+varargs), and it's the C++ "idiomatic" way to perform IO, so you should use it unless you have specific needs not to do so.
Basically, cout
is the C++ way of outputting to standard output while printf
is the C way.
C++ iostreams (of which cout
is one) are based on C++ classes and are extensible to handle new classes. In other words, you can create a class called foo
and then do:
foo bar;
std::cout << bar << std::endl;
On the other hand, printf
cannot handle new types, you have to write functions which call printf
for each of the components of that type, where each component is already a type known to printf
(such as int
or char *
).
There's really no excuse for using printf
in C++ code. I always say that, if you're going to use C++, you should use it, not wallow in the old world :-) If you want to use printf
, stick with C.
If you're looking for an example of how to allow your class to be used in iostreams, see an answer I provided to an earlier question regarding the code that does it.
taken from http://forums.devshed.com/c-programming-42/difference-between-cout-and-printf-38373.html
cout is an object of the iostream in C++. If you are using C++, then use cout, it works well. printf while doing some the same things, it is a formatting function that prints to the standard out. This is mainly used in C.
so printf is the big brother of cout in a way, as it allows you to format strings.
精彩评论