我正在使用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;
}