10

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);
roalz
  • 2,699
  • 3
  • 25
  • 42
Mikhail
  • 7,749
  • 11
  • 62
  • 136

2 Answers2

19

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";
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
GWW
  • 43,129
  • 11
  • 115
  • 108
  • 4
    Even better, `rdbuf(streambuf*)` returns the old buffer, so you don't even need separate calls to get the old one and set a new one. – John Flatness Oct 11 '11 at 03:23
  • @John Flatness: Oh thanks I didn't notice that in the docs. Fixed my answer. – GWW Oct 11 '11 at 03:26
1

Why precisely do you not want to redirect the output? If it is because there is other output you wish to keep, you may be out of luck.

If it is just so you don't have to type a complex shell expression on a terminal in a demo, I suggest making a start script and doing the redirect inside.

That, or reopen stdout to /dev/null somewhere near the top of main.

phs
  • 10,687
  • 4
  • 58
  • 84