【问题标题】:Display a custom help message in TCLAP在 TCLAP 中显示自定义帮助消息
【发布时间】:2016-01-01 13:08:21
【问题描述】:

我正在使用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 运行时。

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

我怎样才能做到这一点?

【问题讨论】:

  • 你想要什么?我一直认为 automagic 帮助创作是核心力量——但有时我将输出子类化以使其更紧凑,即发烧空行。
  • 我想打印一大段我自己编写和格式化的文本。
  • 完全可行。将 TCLAP 子类化为 myTCLAP,将默认帮助方法替换为自定义方法,该方法将您的格式化文本作为附加 ctor 参数。

标签: c++ command-line-arguments


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2021-08-07
    • 1970-01-01
    • 2015-07-26
    • 2021-10-03
    相关资源
    最近更新 更多