2015-10-04 90 views
1

我正在使用TCLAP庫來執行一些命令行參數分析。這非常棒:除了它打印的幫助信息外。那些很醜陋。在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運行。

我想要更多的創意控制:我想讓我自己的幫助信息!

我該如何做到這一點?

+0

你想要什麼?我一直認爲_automagic_幫助創作是一個核心力量 - 但我有時會將輸出分類以使其更加緊湊,即發熱的空白線條。 –

+0

我想打印一大塊我自己編寫和格式化的文本。 – Richard

+0

完全可行。將TCLAP子類轉換爲myTCLAP,將默認幫助方法替換爲將格式化文本作爲附加ctor參數的自定義幫助方法。 –

回答

0

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; 
} 
相關問題