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""?
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.
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.
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.
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).
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With