C++ 命令行解析库Tclap

http://tclap.sourceforge.net/

一个官方demo:test1.cpp

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

using namespace TCLAP;
using namespace std;

int main(int argc, char** argv)
{
        // Wrap everything in a try block.  Do this every time, 
        // because exceptions will be thrown for problems. 
        try {

        // Define the command line object.
        CmdLine cmd("Command description message", ' ', "0.9");

        // Define a value argument and add it to the command line.
        ValueArg<string> nameArg("n","name","Name to print",true,"homer","string");
        cmd.add( nameArg );

        // Define a switch and add it to the command line.
        SwitchArg reverseSwitch("r","reverse","Print name backwards", false);
        cmd.add( reverseSwitch );

        // Parse the args.
        cmd.parse( argc, argv );

        // Get the value parsed by each arg. 
        string name = nameArg.getValue();
        bool reverseName = reverseSwitch.getValue();

        // Do what you intend too...
        if ( reverseName )
        {
                reverse(name.begin(),name.end());
                cout << "My name (spelled backwards) is: " << name << endl;
        }
        else
                cout << "My name is: " << name << endl;


        } catch (ArgException &e)  // catch any exceptions
        { cerr << "error: " << e.error() << " for arg " << e.argId() << endl; }
}


                     

效果:

[leajon@arch examples]$ ./test1
PARSE ERROR:  
             Required argument missing: name

Brief USAGE: 
   ./test1  [-r] -n <string> [--] [--version] [-h]

For complete USAGE and HELP type: 
   ./test1 --help

[leajon@arch examples]$ ./test1 -n tclap -r
My name (spelled backwards) is: palct
posted @ 2012-08-07 22:29  Leo Forest  阅读(2714)  评论(0编辑  收藏  举报