Search code examples
c++ostream

Controlling print outs in a program with command line argument


I am trying to control the print outs in my program. I wrote a small script for that which takes a command line argument and decides to print or not to print depending upon the flag -v passed to it. Now I have to write out(bool) in my actual program everywhere. Is it possible to make the decision in the start of the program and just to use out instead of out(bool).

class mystreambuf : public std::streambuf
{
};
mystreambuf nostreambuf;
std::ostream nocout(&nostreambuf);
#define out(b) ((b==true)?std::cout : nocout )

int main(int argc, char* argv[])
{

    std::cout << "Program name is: " << argv[0] << "\n";

    int counter;
    bool verbose;

    if (argc == 1)
    {
        std::cout << "No command line argument passed" << argv[0] << "\n";
    }

    if (argc >= 2)
    {
        for (counter = 0; counter < argc; counter++)
        {
            std::cout << "Argument passed are: " << argv[counter] << "\n";
            if (strcmp(argv[counter], "-v") == 0)
            {
                verbose = true;
            }
            else
            {
                verbose = false;
            }
        }
    }

    out(verbose) << "\n hello world \n";

    system("pause");
}

Solution

  • A simple way would be to build a minimal class containing the boolean flag and a reference to the actual stream. Then the << operator would be either a no-op or a delegation to the actual stream. It could be:

    class LogStream {
        std::ostream& out;
        bool verbose;
    public:
        LogStream(std::ostream& out = std::cout): out(out) {}
        void set_verbose(bool verbose) {
        this->verbose = verbose;
        }
        template <class T>
        LogStream& operator << (const T& val) {
        if (verbose) {
            out << val;
        }
        return *this;
        }
    };
    

    It can then be used that way:

    int main(int argc, char* argv[])
    {
    
        LogStream out;
        ...
        out.set_verbose(verbose);
        out << "\n hello world \n";
        ...
    }