Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable cout output in the runtime?

Tags:

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""?

like image 393
user3639557 Avatar asked May 12 '15 07:05

user3639557


People also ask

How do you stop cout without a new line?

The cout operator does not insert a line break at the end of the output. One way to print two lines is to use the endl manipulator, which will put in a line break. The new line character \n can be used as an alternative to endl. The backslash (\) is called an escape character and indicates a special character.

Does cout slow program?

It's almost certainly true. Writing to the terminal is notorious for slowing things down. Run your program and redirect the output to a file and see how much faster it is.

Why is cout so slow?

As for why it is so "time consuming", (in other words, slow,) that's because the primary purpose of std::cout (and ultimately the operating system's standard output stream) is versatility, not performance.

What is STD cout?

std::cout is used to output a value (cout = character output) std::cin is used to get an input value (cin = character input) << is used with std::cout, and shows the direction that data is moving (if std::cout represents the console, the output data is moving from the variable to the console).


2 Answers

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.

like image 161
user703016 Avatar answered Oct 05 '22 11:10

user703016


To supress output, you can disconnect the underlying buffer from cout.

#include <iostream>  using namespace std;  int main(){      // get underlying buffer     streambuf* orig_buf = cout.rdbuf();      // set null     cout.rdbuf(NULL);      cout << "this will not be displayed." << endl;      // restore buffer     cout.rdbuf(orig_buf);      cout << "this will be dispalyed." << endl;      return 0; } 
like image 29
911 Avatar answered Oct 05 '22 12:10

911