c++命令行解析库cmdline使用
之前用过 getopt 函数对主函数参数进行解析,后发现了 cmdline 这个库——说是库,实际只是一个头文件,非常方便集成到程序中。本文对此库进行简单测试。
·
之前用过 getopt 函数对主函数参数进行解析,后发现了 cmdline 这个库——说是库,实际只是一个头文件,非常方便集成到程序中。本文对此库进行简单测试。
下载编译
cmdline 库地址为:https://github.com/tanakh/cmdline 。
可直接下载 cmdline.h 头文件使用,也可以下载仓库,编译其中的测试示例。
测试
测试代码
测试代码如下:
/*
如果解析不存在的参数,会报段错误,最好加默认值
TODO:添加子命令,类似 git log、git status 这样的
*/
#include "cmdline.h"
#include <stdio.h>
#include <iostream>
using namespace std;
bool g_bPrint = false;
// 有些帮助信息过多,使用函数组装
char* getHelp(int type)
{
static char info[256] = {0};
if (type == 't')
{
sprintf(info,
" test type \n \
autotest - for auto test\n \
dualtest - for dual version test\n \
more comming up...");
}
return info;
}
int main(int argc, char *argv[])
{
cmdline::parser theArgs;
theArgs.add<string>("test", 't', getHelp('t'), false, "auto");
theArgs.add<string>("host", 'h', "host name", false, ""); // 如果为 true,则必须带该参数,否则无法解析失败
theArgs.add<int>("rate", 'r', "rate number", false, 80, cmdline::range(1, 65535)); // 带默认值、范围的
theArgs.add("print", 'p', "show message"); // bool 型,需要判断是否存在,存在则置标志为true
//theArgs.add("help", 0, "print this message1111");
//theArgs.footer("filename ...");
//theArgs.set_program_name("mytool");
theArgs.set_program_name(argv[0]);
// 调整位置,让cmdline误以为第二个参数才是命令
theArgs.parse_check(argc-1, &argv[1]);
try{
printf("test type: %s\n", theArgs.get<string>("test").c_str());
} catch(const std::exception &e){}
try{
printf("bad: %s\n", theArgs.get<string>("bad").c_str()); // 不存在的参数
} catch(const std::exception &e){
printf("param [bad] not exist...\n");
}
try{
printf("host: %s\n", theArgs.get<string>("host").c_str());
} catch(const std::exception &e){}
try{
printf("rate: %d\n", theArgs.get<int>("rate"));
} catch(const std::exception &e){}
try{
printf("rest args: \n");
for (int i = 0; i < (int)theArgs.rest().size(); i++)
{
//cout << theArgs.rest()[i] << endl;
printf("%s\n", theArgs.rest()[i].c_str());
}
} catch(const std::exception &e){}
// 此法不能判断不存在的参数
// if (theArgs.exist("type"))
// {
// printf("type111: %d\n", theArgs.get<string>("type").c_str());
// }
//
if (theArgs.exist("rate")) // 非bool类型,似乎也不能如此判断
{
printf("rate111: %d\n", theArgs.get<int>("rate"));
}
if (theArgs.exist("print"))
{
g_bPrint = false;
}
return 0;
}
输出结果如下:
$ ./a.out
argument number must be longer than 0
usage: ./a.out [options] ...
options:
-t, --test test type
autotest - for auto test
dualtest - for dual version test
more comming up... (string [=auto])
-h, --host host name (string [=])
-r, --rate rate number (int [=80])
-p, --print show message
-?, --help print this message
$ ./a.out -r 100 -h latelee.org
test type: auto
param [bad] not exist...
host: latelee.org
rest args:
100
更多推荐
所有评论(0)