【问题标题】:Controlling print outs in a program with command line argument使用命令行参数控制程序中的打印输出
【发布时间】:2018-07-10 08:34:35
【问题描述】:

我正在尝试控制我的程序中的打印输出。我为此编写了一个小脚本,它接受命令行参数并根据传递给它的标志-v 决定打印或不打印。现在我必须在我的实际程序中到处写out(bool)。是否可以在程序开始时做出决定,只使用out 而不是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");
}

【问题讨论】:

  • 这听起来你真正需要的是一个日志框架......
  • 作为一般规则,避免在代码中使用常量truefalse,它们实际上总是不必要的,只会增加冗长,从而降低可读性。不要写b == true,只写b。对于您的(具有讽刺意味的)verbose 分配也是如此:这可以而且应该在一行中完成(而不是 eight):verbose = strcmp(argv[counter], "-v") == 0; — 此外,out 应该是一个函数,而不是一个宏。

标签: c++ ostream


【解决方案1】:

一种简单的方法是构建一个包含布尔标志和对实际流的引用的最小类。那么&lt;&lt; 操作符要么是空操作,要么是对实际流的委托。可能是:

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

然后可以这样使用:

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

    LogStream out;
    ...
    out.set_verbose(verbose);
    out << "\n hello world \n";
    ...
}

【讨论】:

    【解决方案2】:

    您可以创建一个在开始时设置并登录的单例实例。比如:

    class Printer {
        public: static std::streambuf getInstance() {
            if (_instance._printing) {
               return std::cout;
            }
            return _instance._nostreambuf;
        }
        static void setPrinting(bool set) {
            _instance._printing = set;
        }
        private:
        static Printer _instance;
        mystreambuf _nostreambuf;
        bool _printing;
        // delete constructors and assignment operators.
    }
    

    注意:快速伪代码,未经测试。

    你会使用喜欢的:

    Printer::setPrinting(verboseBool);
    Printer::getInstance() << "Print text";
    

    但是你要做的是一个记录器。其中有很多。 Here is a nice list.

    【讨论】:

      【解决方案3】:

      只需将 out 设为两个选项之一的变量:

      std::ostream &out = verbose ? std::cout : nocout;
      

      并使用out &lt;&lt; 继续打印

      【讨论】:

        猜你喜欢
        • 2020-08-09
        • 2021-03-12
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 2013-10-10
        • 2012-06-10
        • 2020-01-06
        • 2019-06-08
        相关资源
        最近更新 更多