Search code examples
c++coutostream

Programmatically Ignore Cout


Does anybody know if there is a trick to toggle all the cout << functions to not print out visible output? I am trying to hack together some code written by me and some other people to put together a demo. I would rather not redirect the output to a file and would like a solution that had some measure of compatibility between Windows and Linux.

In my scenario I have many many lines of code with with various #defines controlling when certain methods produce debug output. I want to call something like:

cout.off();
driverForAffectA();
driverForAffectB();
cout.on();
printSpecializedDebug();
exit(0);

Solution

  • You can change cout's stream buffer.

    streambuf *old = cout.rdbuf();
    cout.rdbuf(0);
    cout << "Hidden text!\n";
    cout.rdbuf(old);
    cout << "Visible text!\n";
    

    Edit:

    Thanks to John Flatness' comment you can shorten the code a bit:

    streambuf *old = cout.rdbuf(0);
    cout << "Hidden text!\n";
    cout.rdbuf(old);
    cout << "Visible text!\n";