gpt4 book ai didi

c++ - 在 TCLAP 中显示自定义帮助消息

转载 作者:太空狗 更新时间:2023-10-29 21:39:26 63 4
gpt4 key购买 nike

我正在使用 TCLAP库来做一些命令行参数解析。它非常棒:除了它打印的帮助信息。那些有点丑。

例如,这是输出:

USAGE: 

./a.out [-r] -n <string> [--] [--version] [-h]


Where:

-r, --reverse
Print name backwards

-n <string>, --name <string>
(required) Name to print

--, --ignore_rest
Ignores the rest of the labeled arguments following this flag.

--version
Displays version information and exits.

-h, --help
Displays usage information and exits.


Command description message

这个程序:

#include <string>
#include <iostream>
#include <algorithm>
#include <tclap/CmdLine.h>

int main(int argc, char** argv){
try {
TCLAP::CmdLine cmd("Command description message", ' ', "0.9");
TCLAP::ValueArg<std::string> nameArg("n","name","Name to print",true,"homer","string");

cmd.add( nameArg );
TCLAP::SwitchArg reverseSwitch("r","reverse","Print name backwards", cmd, false);
cmd.parse( argc, argv );

std::string name = nameArg.getValue();
bool reverseName = reverseSwitch.getValue();

if ( reverseName ){
std::reverse(name.begin(),name.end());
std::cout << "My name (spelled backwards) is: " << name << std::endl;
} else{
std::cout << "My name is: " << name << std::endl;
}
} catch (TCLAP::ArgException &e) {
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
}
}

当使用 ./a.out -h 运行时。

我想要更多的创意控制:我想制作我自己的帮助信息!

我怎样才能做到这一点?

最佳答案

TCLAP::CmdLineOutput 类负责打印帮助(或用法)消息。

如果您希望 TCLAP 打印自定义消息,您必须首先从上述类派生并将其实例添加到您的 TCLAP::CmdLine 对象中,例如:

cmd.setOutput(new CustomHelpOutput());

这里是自定义 TCLAP::CmdLineOutput 的示例:

class CustomHelpOutput : public TCLAP::StdOutput {
public:
virtual void usage(TCLAP::CmdLineInterface& _cmd) override {
std::cout << "My program is called " << _cmd.getProgramName() << std::endl;
}
};

请注意,您是负责在您的自定义对象之后进行清理的人,因为 TCLAP 有一个禁用其删除的标志 in the setter .

inline void CmdLine::setOutput(CmdLineOutput* co)
{
if ( !_userSetOutput )
delete _output;
_userSetOutput = true;
_output = co;
}

关于c++ - 在 TCLAP 中显示自定义帮助消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32939077/

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