tags:

views:

821

answers:

7

What is the difference between printf and cout in C++?

+15  A: 

And I quote:

In high level terms, the main differences are type safety (cstdio doesn't have it), performance (most iostreams implementations are slower than the cstdio ones) and extensibility (iostreams allows custom output targets and seamless output of user defined types).

Kyle Rozendo
+6  A: 

One is a function, that prints to stdout. The other is an object that provides several member functions and overloads of operator<< that print to stdout. There are many more differences that I could enumeration, but I'm not sure what you are after.

Marcelo Cantos
This is definitely the key difference!
pdbartlett
A: 
cout<< "Hello";
printf("%s", "Hello"); 

Both are used to print values. They have completely different syntax. C++ has both, C only has printf.

scatman
... what? did you mixup something?
xtofl
Sometimes SO depresses me.
anon
Fixed the issue. -1 because it required fixing and the answer leaves a lot to be desired.
Yacoby
The function names had been reversed: cout was used with the printf syntax, and printf was used with the cout syntax. Shouldn't have even been accepted!
Computer Guru
The main advantage of cout is that it uses operator<< which can be overloaded for complex types
Opera
and the main disadvantage of cout is that it uses operator<< which is verbose and ugly and arguably operator abuse. :)
jalf
I'm a little confused. Why was this answer accepted with a -6 vote?
Xavier Ho
It was first positive and then quickly dropped because of the incorrect example
PoweRoy
Riiiight.. still strange.
Xavier Ho
(why am i still on this thread..!@!#) the example is correct syntactically AFAIK. Problem with this answer is that there are plenty of differences, not just syntax :)
mishal153
There should be a badge for worst answer but selected as correct.
Ed Swangren
Although this is certainty not the best answer, I don't understand how scatman is being punished for his answer only because it was picked as the best answer. xbit has a way worse answer IMO but has -1 vote. I'm not saying xbit should be down voted any more, but I don't see it being fair to down vote scatman for the OP's mistake anymore than it has to be...
Jesse
@Jesse: the downvotes are because the first revision of the answer was *completely* wrong. And most of the people who downvoted then haven't seen that it's been fixed since then. I just cancelled my downvote.
jalf
@jalf ah okay that makes sense. Thanks :)
Jesse
+30  A: 

From the C++ FAQ [http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.1]:

[15.1] Why should I use <iostream> instead of the traditional <cstdio>?

Increase type safety, reduce errors, allow extensibility, and provide inheritability.

printf() is arguably not broken, and scanf() is perhaps livable despite being error prone, however both are limited with respect to what C++ I/O can do. C++ I/O (using << and >>) is, relative to C (using printf() and scanf()):

  • More type-safe: With <iostream>, the type of object being I/O'd is known statically by the compiler. In contrast, <cstdio> uses "%" fields to figure out the types dynamically.
  • Less error prone: With <iostream>, there are no redundant "%" tokens that have to be consistent with the actual objects being I/O'd. Removing redundancy removes a class of errors.
  • Extensible: The C++ <iostream> mechanism allows new user-defined types to be I/O'd without breaking existing code. Imagine the chaos if everyone was simultaneously adding new incompatible "%" fields to printf() and scanf()?!
  • Inheritable: The C++ <iostream> mechanism is built from real classes such as std::ostream and std::istream. Unlike <cstdio>'s FILE*, these are real classes and hence inheritable. This means you can have other user-defined things that look and act like streams, yet that do whatever strange and wonderful things you want. You automatically get to use the zillions of lines of I/O code written by users you don't even know, and they don't need to know about your "extended stream" class.

OTOH, printf is significantly faster [see, for example, http://programming-designs.com/2009/02/c-speed-test-part-2-printf-vs-cout/]

Mikeage
On the other other hand, there's the FastFormat library (http://www.fastformat.org), offering type-safety, expressivity and performance at once. (Not that I tried it yet...)
xtofl
How does such a poorly presented piece of copy-pasting, with no consideration for escaping (hence a rash of inexplicable omissions from the text) get _nine_ upvotes?
Marcelo Cantos
There's also Boost.Format, wonder how the two compare.
Matthieu M.
@Marcelo Cantos: I suspect a backlash to the accepted answer.
Gorpik
@xtofl yeah, I looked at it a while ago. Seemed promising, but rated dangerously high on my annoy-o-meter when I realized it depends on environment variables, which is one thing I really do not care to set up just for my code to compile.
jalf
@jalf: I knew there should have been something.... would you mind adding that to this, old, question? http://stackoverflow.com/questions/446276/is-there-a-catch-with-fastformat
xtofl
@Marcelo probably because it's a good summary, with everything cited. The formatting... yeah, that's pretty bad. I should have fixed that myself, but it appears that others (yourself included) took care of it, which, of course, is more constructive than just whining.
Mikeage
+5  A: 

People often claim that printf is much faster. This is largely a myth. I just tested it, with the following results:

cout with only endl                     1461.310252 ms
cout with only '\n'                      343.080217 ms
printf with only '\n'                     90.295948 ms
cout with string constant and endl      1892.975381 ms
cout with string constant and '\n'       416.123446 ms
printf with string constant and '\n'     472.073070 ms
cout with some stuff and endl           3496.489748 ms
cout with some stuff and '\n'           2638.272046 ms
printf with some stuff and '\n'         2520.318314 ms

Conclusion: if you want only newlines, use printf; otherwise, cout is almost as fast, or even faster. More details can be found on my blog.

To be clear, I'm not trying to say that iostreams are always better than printf; I'm just trying to say that you should make an informed decision based on real data, not a wild guess based on some common, misleading assumption.

Update: Here's the full code I used for testing. Compiled with g++ without any additional options (apart from -lrt for the timing).

#include <stdio.h>
#include <iostream>
#include <ctime>

class TimedSection {
    char const *d_name;
    timespec d_start;
    public:
        TimedSection(char const *name) :
            d_name(name)
        {
            clock_gettime(CLOCK_REALTIME, &d_start);
        }
        ~TimedSection() {
            timespec end;
            clock_gettime(CLOCK_REALTIME, &end);
            double duration = 1e3 * (end.tv_sec - d_start.tv_sec) +
                              1e-6 * (end.tv_nsec - d_start.tv_nsec);
            std::cerr << d_name << '\t' << std::fixed << duration << " ms\n"; 
        }
};

int main() {
    const int iters = 10000000;
    char const *text = "01234567890123456789";
    {
        TimedSection s("cout with only endl");
        for (int i = 0; i < iters; ++i)
            std::cout << std::endl;
    }
    {
        TimedSection s("cout with only '\\n'");
        for (int i = 0; i < iters; ++i)
            std::cout << '\n';
    }
    {
        TimedSection s("printf with only '\\n'");
        for (int i = 0; i < iters; ++i)
            printf("\n");
    }
    {
        TimedSection s("cout with string constant and endl");
        for (int i = 0; i < iters; ++i)
            std::cout << "01234567890123456789" << std::endl;
    }
    {
        TimedSection s("cout with string constant and '\\n'");
        for (int i = 0; i < iters; ++i)
            std::cout << "01234567890123456789\n";
    }
    {
        TimedSection s("printf with string constant and '\\n'");
        for (int i = 0; i < iters; ++i)
            printf("01234567890123456789\n");
    }
    {
        TimedSection s("cout with some stuff and endl");
        for (int i = 0; i < iters; ++i)
            std::cout << text << "01234567890123456789" << i << std::endl;
    }
    {
        TimedSection s("cout with some stuff and '\\n'");
        for (int i = 0; i < iters; ++i)
            std::cout << text << "01234567890123456789" << i << '\n';
    }
    {
        TimedSection s("printf with some stuff and '\\n'");
        for (int i = 0; i < iters; ++i)
            printf("%s01234567890123456789%i\n", text, i);
    }
}
Thomas
"more details on your blog"? Hardly. Your blog is missing the same details as this post: it doesn't tell us what you tested or how you tested it.
jalf
@jalf: You think? I linked instead of posting the full code here, because it's a bit long and repetitive. I definitely wrote there what I tested and how... the text on my blog should be sufficient to reproduce the code. But I've edited it into my post... is that sufficient?
Thomas
In your scores printf beats cout easily (majority cases). I wonder why you recommend using cout when it comes to perf. Though I agree perf is not too different in realistic cases..
mishal153
@mishal153: I'm just trying to say that the performance is not too different, so the commonly-heard advice of "never use cout because it's waaay slow" is plain stupid. Note that cout has the obvious advantage of type-safety, and often readability as well. (Floating-point formatting with iostreams is horrible...)
Thomas
@Thomas: "reproducing the code" wouldn't necessarily reproduce your results. In order to know if your benchmarks are valid, we need to be able to look at the code. But yeah, thanks for adding the code. :)
jalf
@Thomas: I tested your code on a Ubuntu 10.04 (gcc 4.4.3), and came out with similar results (note that the cout was somewhat faster than printf for small strings like `"\n"`).
paercebal
+1 for the tests, and the results.
paercebal
+4  A: 

For me, the real differences which would make me go for 'cout' rather than 'printf' are:

1) << operator can be overloaded for my classes.

2) Output stream for cout can be easily changed to a file : (: copy paste :)

#include <iostream>
#include <fstream>
using namespace std;

int main ()
{
    cout << "This is sent to prompt" << endl;
    ofstream file;
    file.open ("test.txt");
    streambuf* sbuf = cout.rdbuf();
    cout.rdbuf(file.rdbuf());
    cout << "This is sent to file" << endl;
    cout.rdbuf(sbuf);
    cout << "This is also sent to prompt" << endl;
    return 0;
}

3) I find cout more readable, especially when we have many parameters.

One problem with cout is the formatting options. Formatting the data (precision, justificaton, etc.) in printf is easier.

mishal153
A: 

With primitives, it probably doesn't matter entirely which one you use. I say where it gets usefulness is when you want to output complex objects.

For example, if you have a class,

#include <iostream>
#include <cstdlib>

using namespace std;

class Something
{
public:
        Something(int x, int y, int z) : a(x), b(y), c(z) { }
        int a;
        int b;
        int c;

        friend ostream& operator<<(ostream&, const Something&);
};

ostream& operator<<(ostream& o, const Something& s)
{
        o << s.a << ", " << s.b << ", " << s.c;
        return o;
}

int main(void)
{
        Something s(3, 2, 1);

        // output with printf
        printf("%i, %i, %i\n", s.a, s.b, s.c);

        // output with cout
        cout << s << endl;

        return 0;
}

Now the above might not seem all that great, but let's suppose you have to output this in multiple places in your code. Not only that, let's say you add a field "int d." With cout, you only have to change it in once place. However, with printf, you'd have to change it in possibly a lot of places and not only that, you have to remind yourself which ones to output.

With that said, with cout, you can reduce a lot of times spent with maintenance of your code and not only that if you re-use the object "Something" in a new application, you don't really have to worry about output.

Daniel
Also, to add about the performance thing, I'd say that you shouldn't output anything at all if your application is made for performance. Any sort of output to std is rather expensive and slow. I say you should avoid it and only output when it is absolutely necessary to do so.
Daniel