gpt4 book ai didi

c++ - 使用命令行参数控制程序中的打印输出

转载 作者:行者123 更新时间:2023-11-30 03:22:18 27 4
gpt4 key购买 nike

我试图在我的程序中控制打印输出。我为此编写了一个小脚本,它接受一个命令行参数并根据传递给它的标志 -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");
}

最佳答案

一个简单的方法是构建一个包含 bool 标志和对实际流的引用的最小类。然后 <<运算符要么是空操作,要么是对实际流的委托(delegate)。可能是:

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

关于c++ - 使用命令行参数控制程序中的打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51260634/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com