How to quickly get rid of std :: cout

I have inherited a large codebase where std::cout

it is very often used for the purpose of printing debug information. There is no real debug / log functionality in the code, and since it will be a short-lived task (fix) implementing the debug / log functionality is out of the question at this point.

I'm really worried about the amount of text this program outputs, and at least until I work on it, I'd like to disable all printouts on a temporary basis.

At the moment I see two solutions:

  • just comment them out ... it's a lot of work because some of them std::couts

    span multiple lines so I would have to find them manually.
  • replace all occurrences std::cout

    with a construct that has its own operator <<

    and just swallows all weekend

Do you have a better solution for this problem?

0


source to share


4 answers


You can programmatically redirect stdout with something like

FILE origSTDOUT = *stdout;
static FILE* nul = fopen( "NUL", "w" );
*stdout = *nul;
setvbuf( stdout, NULL, _IONBF, 0 );

      

from the point you want to suppress and restore with something like



*stdout = origSTDOUT;

      

to restore it.

+2


source


From the app

If you want to do this from within the application itself, you can change the baseline so that any output effectively ends up somewhere else.std::streambuf

std::cout


Example

std::ostringstream buffer;
std::streambuf * cout_streambuf = std::cout.rdbuf (buffer.rdbuf ()); // (A)

      

std::cout << "hello world\n";                                        // (B) 

      

std::cout.rdbuf (orig_cout_streambuf);                               // (C)

      

  • (A) will set the underlying streambuf std::cout

    to value buffer

    and return the old streambuf (effectively initializes cout_streambuf to this value).
  • (B) write some data effectively doing it in our std::ostreamstream

  • (C) reset the base streambuf back to the previous state



Note : (B) represents the part of your application where you want to have "redirected std :: cout".



Using shell redirection

Instead of fiddling with the application itself, you can use the facilities provided by your shell and simply redirect the output to STDOUT to, /dev/null

or equivalent (effectively discarding it)


* NIX

./binary > /dev/null # send STDOUT to /dev/null

      


WINDOWS

./binary > NUL       # send STDOUT to NUL

      

+2


source


It:

std::cout.rdbuf(nulllptr);

      

Disables any output. Just add it to the main menu.

+1


source


You can redirect standard output to a null file. Thus, the exits become invisible. On Unix systems, you can run your program like this: program_name > /dev/null

on the console. For windows, you can tryprogram_name > nul

0


source







All Articles