How to get rid of std::cout quickly

跟風遠走 提交于 2019-12-12 06:04:16

问题


I have inherited a large codebase where std::cout is very frequently used with the purpose of printing out debugging information. There is no real debug/log functionality in the code and since this will be a short lived task (bugfix) implementing debug/log functionality for now is out of the question.

It really bothers me the amount of text this program outputs, and at least till I have to work on it I would like to disable all the printouts on a temporary basis.

I see two solutions for now:

  1. just comment them out... this is a lot of work because some of the std::couts span accross multiple line, so I would have to find them manually
  2. replace all occurences of std::cout with a construct that has its own operator << and simply swallows all the output

Do you have a better solution for this problem?


回答1:


You can redirect stdout programmatically 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 output and restore with something like

*stdout = origSTDOUT;

to restore it.




回答2:


From within the application

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

  • cppreference.com - std::basic_ios::rdbuf

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 of std::cout to that of buffer, and return the old streambuf (effectively initializing cout_streambuf with this value).
  • (B) write some data, effectively making it end up in our std::ostreamstream
  • (C) reset the underlying streambuf, reverting to the previous state


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



Using shell redirects

Instead of messing around with the application itself you could 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



回答3:


This:

std::cout.rdbuf(nulllptr);

Disables any output. Just add it to main.




回答4:


You can redirect standard output to a null file. So, the outputs become invisible. In Unix systems, you can run your program like this: program_name > /dev/null on a console. For windows, you can try program_name > nul



来源:https://stackoverflow.com/questions/29072499/how-to-get-rid-of-stdcout-quickly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!