How to disable cout output in the runtime?

user3639557 picture user3639557 · May 12, 2015 · Viewed 19.7k times · Source

I often use cout for debugging purpose in many different places in my code, and then I get frustrated and comment all of them manually.

Is there a way to suppress cout output in the runtime?

And more importantly, let's say I want to suppress all cout outputs, but I still want to see 1 specific output (let's say the final output of the program) in the terminal.

Is it possible to use an ""other way"" of printing to the terminal for showing the program output, and then when suppressing cout still see things that are printed using this ""other way""?

Answer

user703016 picture user703016 · May 12, 2015

Sure, you can (example here):

int main() {
    std::cout << "First message" << std::endl;

    std::cout.setstate(std::ios_base::failbit);
    std::cout << "Second message" << std::endl;

    std::cout.clear();
    std::cout << "Last message" << std::endl;

    return 0;
}

Outputs:

First message
Last message

This is because putting the stream in fail state will make it silently discard any output, until the failbit is cleared.