How to disable cout output in the runtime? - c++

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

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;
}

Don't use cout for debugging purposes, but define a different object (or function, or macro) that calls through to it, then you can disable that function or macro in one single place.

You can user cerr - standard output stream for errors for your debug purposes.
Also, there is clog - standard output stream for logging.
Typically, they both behave like a cout.
Example:
cerr << 74 << endl;
Details: http://www.cplusplus.com/reference/iostream/cerr/
http://www.cplusplus.com/reference/iostream/clog/

If you include files which involve cout you may want to write the code at the start (outside of main), which can be done like this:
struct Clearer {
Clearer() { std::cout.setstate(std::ios::failbit); }
} output_clearer;

It seems you print debug messages. You could use TRACE within Visual C++/MFC or you just might want to create a Debug() function which takes care of it. You can implement it to turn on only if a distinct flag is set. A lot of programs use a command line parameter called verbose or -v for instance, to control the behavior of their log and debug messages.

Related

I have a problem with output in C++, two last prints do not work [duplicate]

Is there any circumstance when std::cout << "hello" doesn't work? I have a c/c++ code, however the std::cout doesn't print anything, not even constant strings (such as "hello").
Is there any way to check if cout is able/unable to open the stream? There are some member functions like good(), bad(), ... but I don't know which one is suitable for me.
Make sure you flush the stream. This is required because the output streams are buffered and you have no guarantee over when the buffer will be flushed unless you manually flush it yourself.
std::cout << "Hello" << std::endl;
std::endl will output a newline and flush the stream. Alternatively, std::flush will just do the flush. Flushing can also be done using the stream's member function:
std::cout.flush();
std::cout won't work on GUI apps!
Specific to MS Visual Studio:
When you want a console application and use MS Visual Studio, set project property "Linker -> System -> SubSystem" to Console. After creating a new Win32 project (for a native C++ app) in Visual Studio, this setting defaults to "Windows" which prevents std::cout from putting any output to the console.
To effectively disable buffering you can call this:
std::setvbuf(stdout, NULL, _IONBF, 0);
Alternatively, you can call your program and disable output buffering in the command line:
stdbuf -o 0 ./yourprogram --yourargs
Keep in mind this is not usually done for performance reasons.
It is probable that std::cout doesn't work due to buffering (what you're writing ends up in the buffer of std::cout instead of in the output).
You can do one of these things:
flush std::cout explicitly:
std::cout << "test" << std::flush; // std::flush is in <iostream>
std::cout << "test";
std::cout.flush(); // explicitly flush here
std::cout << "test" << std::endl; // endl sends newline char(s) and then flushes
use std::cerr instead. std::cerr is not buffered, but it uses a different stream (i.e. the second solution may not work for you if you're interested in more than "see message on console").

How to disable std::clog logging from source code?

When developing code, I have many console logging (std::clog) and some console output (std::cout). But now, I wanted to do online submission of my source code and I want to disable all the console logging (clog) but keep the console output (cout)
I can surely comment all of my //std::clog, but is there a better way to disable all logging inside my source file,?
You can redirect clog, create your own ofstream and use rdbuf function.
std::ofstream nullstream;
std::clog.rdbuf(nullstream.rdbuf());
Copied from Andreas Papadopoulos' answer to a slightly different question -- be sure to upvote him there!
Sure, you can (example here):
int main() {
std::clog << "First message" << std::endl;
std::clog.setstate(std::ios_base::failbit);
std::clog << "Second message" << std::endl;
std::clog.clear();
std::clog << "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.

Most efficient way to output a newline

I was wondering what is the most efficient performant way to output a new line to console. Please explain why one technique is more efficient. Efficient in terms of performance.
For example:
cout << endl;
cout << "\n";
puts("");
printf("\n");
The motivation for this question is that I find my self writing loops with outputs and I need to output a new line after all iterations of the loop. I'm trying to find out what's the most efficient way to do this assuming nothing else matters. This assumption that nothing else matters is probably wrong.
putchar('\n') is the most simple and probably fastest. cout and printf with string "\n" work with null terminated string and this is slower because you process 2 bytes (0A 00). By the way, carriage return is \r = 13 (0x0D). \n code is Line Feed (LF).
You don't specify whether you are demanding that the update to the screen is immediate or deferred until the next flush. Therefore:
if you're using iostream io:
cout.put('\n');
if you're using stdio io:
std::putchar('\n');
The answer to this question is really "it depends".
In isolation - if all you're measuring is the performance of writing a '\n' character to the standard output device, not tweaking the device, not changing what buffering occurs - then it will be hard to beat options like
putchar('\n');
fputchar('\n', stdout);
std::cout.put('\n');
The problem is that this doesn't achieve much - all it does (assuming the output is to a screen or visible application window) is move the cursor down the screen, and move previous output up. Not exactly a entertaining or otherwise valuable experience for a user of your program. So you won't do this in isolation.
But what comes into play to affect performance (however you measure that) if we don't output newlines in isolation? Let's see;
Output of stdout (or std::cout) is buffered by default. For the output to be visible, options include turning off buffering or for the code to periodically flush the buffer. It is also possible to use stderr (or std::cerr) since that is not buffered by default - assuming stderr is also directed to the console, and output to it has the same performance characteristics as stdout.
stdout and std::cout are formally synchronised by default (e.g. look up std::ios_base::sync_with_stdio) to allow mixing of output to stdout and std::cout (same goes for stderr and std::cerr)
If your code outputs more than a set of newline characters, there is the processing (accessing or reading data that the output is based on, by whatever means) to produce those other outputs, the handling of those by output functions, etc.
There are different measures of performance, and therefore different means of improving efficiency based on each one. For example, there might be CPU cycles, total time for output to appear on the console, memory usage, etc etc
The console might be a physical screen, it might be a window created by the application (e.g. hosted in X, windows). Performance will be affected by choice of hardware, implementation of windowing/GUI subsystems, the operating system, etc etc.
The above is just a selection, but there are numerous factors that determine what might be considered more or less performance.
On Ubuntu 15.10, g++ v5.2.1 (and an older vxWorks, and OSE)
It is easy to demonstrate that
std::cout << std::endl;
puts a new line char into the output buffer, and then flushes the buffer to the device.
But
std::cout << "\n";
puts a new line char into the output buffer, and does not output to the device. Some future action will be needed to trigger the output of the newline char in the buffer to the device.
Two such actions are:
std::cout << std::flush; // will output the buffer'd new line char
std::cout << std::endl; // will output 2 new line chars
There are also several other actions that can trigger the flush of the std::cout buffering.
#include <unistd.h> // for Linux
void msDelay (int ms) { usleep(ms * 1000); }
int main(int, char**)
{
std::cout << "with endl and no delay " << std::endl;
std::cout << "with newline and 3 sec delay " << std::flush << "\n";
msDelay(3000);
std::cout << std::endl << " 2 newlines";
return(0);
}
And, per comment by someone who knows (sorry, I don't know how to copy his name here), there are exceptions for some environments.
It's actually OS/Compiler implementation dependent.
The most efficient, least side effect guaranteed way to output a '\n' newline character is to use std::ostream::write() (and for some systems requires std::ostream was opened in std::ios_base::binary mode):
static const char newline = '\n';
std::cout.write(&newline,sizeof(newline));
I would suggest to use:
std::cout << '\n'; /* Use std::ios_base::sync_with_stdio(false) if applicable */
or
fputc('\n', stdout);
And turn the optimization on and let the compiler decide what is best way to do this trivial job.
Well if you want to change the line I'd like to add the simplest and the most common way which is using (endl), which has the added perk of flushing the stream, unlike cout << '\n'; on its own.
Example:
cout << "So i want a new line" << endl;
cout << "Here is your new line";
Output:
So i want a new line
Here is your new line
This can be done for as much new lines you want. Allow me to show an example using 2 new lines, it'll definitely clear all of your doubts,
Example:
cout << "This is the first line" << endl;
cout << "This is the second line" << endl;
cout << "This is the third line";
Output:
This is the first line
This is the second line
This is the third line
The last line will just have a semicolon to close since no newline is needed. (endl) is also chain-able if needed, as an example, cout << endl << endl; would be a valid sequence.

std::cout won't print

Is there any circumstance when std::cout << "hello" doesn't work? I have a c/c++ code, however the std::cout doesn't print anything, not even constant strings (such as "hello").
Is there any way to check if cout is able/unable to open the stream? There are some member functions like good(), bad(), ... but I don't know which one is suitable for me.
Make sure you flush the stream. This is required because the output streams are buffered and you have no guarantee over when the buffer will be flushed unless you manually flush it yourself.
std::cout << "Hello" << std::endl;
std::endl will output a newline and flush the stream. Alternatively, std::flush will just do the flush. Flushing can also be done using the stream's member function:
std::cout.flush();
std::cout won't work on GUI apps!
Specific to MS Visual Studio:
When you want a console application and use MS Visual Studio, set project property "Linker -> System -> SubSystem" to Console. After creating a new Win32 project (for a native C++ app) in Visual Studio, this setting defaults to "Windows" which prevents std::cout from putting any output to the console.
To effectively disable buffering you can call this:
std::setvbuf(stdout, NULL, _IONBF, 0);
Alternatively, you can call your program and disable output buffering in the command line:
stdbuf -o 0 ./yourprogram --yourargs
Keep in mind this is not usually done for performance reasons.
It is probable that std::cout doesn't work due to buffering (what you're writing ends up in the buffer of std::cout instead of in the output).
You can do one of these things:
flush std::cout explicitly:
std::cout << "test" << std::flush; // std::flush is in <iostream>
std::cout << "test";
std::cout.flush(); // explicitly flush here
std::cout << "test" << std::endl; // endl sends newline char(s) and then flushes
use std::cerr instead. std::cerr is not buffered, but it uses a different stream (i.e. the second solution may not work for you if you're interested in more than "see message on console").

G++ compiler: Segfault handling

I'm working on a project where I call a function which triggers a segfault. I fixed this, but during the process I noticed the following.
When my code is of the format;
main(){
...
std::cout << "Looking for segfault\n"; // this does not print
buggyFunction(); // crashes in here
...
}
buggyFunction(){
...
thing_that_causes_segfault;
...
}
The line "Looking for segfault" doesn't print to STD, and the program crashes in buggyFunction. Fine, but when I add a cout line inside buggyFunction();
main(){
...
std::cout << "Looking for segfault\n"; // this now *does* print
buggyFunction();
...
}
buggyFunction(){
...
std::cout << "Now we're INSIDE buggy function\n"; // this prints too
thing_that_causes_segfault;
...
}
Inside buggy function, both lines print (and then it crashes).
Why do we see this difference in ouput, depending on the addition of this extra output call? Is it related to the handling of streams, or something else? I'm using g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3.
The reason for this is that cout has a buffer and it will only pass to the system function and write to the console when the buffer is full. Your second use of cout happens to overflow the buffer and so it calls the operating system and empties the buffer. If you want to guarantee that the output has left the buffer, you must use std::flush. You can both end a line and flush the buffer with std::endl.
Because your line might not immediately printed out because it's cached and the cache is not "flushed". std::endl is an newline + a flush thus forces immediate printout:
std::cout << "Looking for segfault" << std::endl;
It has to do with buffering. Things that you write to cout are appended to an internal buffer that only gets flushed periodically. You can explicitly flush the buffer by writing std::flush to your stream, or replacing the "\n" with << std::endl.