Search code examples
c++command-line-argumentscout

How to write a wrapper function for cout in order to control it by just passing command line arguments?


My aim is to get two forms of output from the program, one with all the print statements that will come into action and the other is the program will operate but there will be no print output. I can do this by writing two different codes, one with cout and other with out it. But I want to create a function that does the job in a single code. It will check for particular command line argument. If true, then cout or else nothing. In this way without editing the code, just by passing additional arguments I can control whether to print anything or not.

I am unable to do anything like that!


Solution

  • You don't need to wrap std::cout. Instead you should create a sink stream, i.e. an output stream that discards all output given to it. You then pass either cout or your sink stream to the functions that generate your output. Creating a sink stream is fairly easy to do.

    #include <ostream>
    #include <streambuf>
    
    class SinkBuffer : public std::streambuf
    {
    };
    
    class SinkStream : public std::ostream
    {
    public:
        SinkStream() : std::ostream(&buffer) {}
    private:
        SinkBuffer buffer;
    };
    

    Then you might use it like this

    static void output(std::ostream& out)
    {
        out << "hello world\n";
    }
    
    int main(int argc, char** argv)
    {
        if (argc >= 2 && strcmp(argv[1], "-q") == 0)
        {
            SinkStream ss;
            output(ss);
        }
        else
        {
            output(std::cout);
        }
    }
    

    This program looks for the command line argument -q and if it finds it uses the sink stream, otherwise it uses std::cout. The effect is that if no command line arguments are passed then the program prints hello world but if -q is passed then it prints nothing.