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

时间:2015-10-04 22:32:53

标签: c++ command-line-arguments

我使用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一起运行。

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

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

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