C++命令行解析库Tclap
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C++命令⾏解析库Tclap ⼀个官⽅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。