【C++】cmdline —— 轻量级的C++命令行解析库
平时用C++写一些命令行工具,须要解析命令行的输入參数,这是一项繁琐而且easy出错的工作,我们不应该将主要精力放在这上面。能够考虑使用开源的库。以下的cmdline就是当中很好用的一款。
cmdline介绍
cmdline 是一个非常easy好用的C++命令行解析库,其基于模板。所以使用非常easy,写出的代码也非常优雅。
因为其仅仅包括一个头文件。所以非常easy集成到自己的项目中。
cmdline项目托管地址Github:https://github.com/tanakh/cmdline
cmdline使用
以下是cmdline项目首页给出的演示样例代码,我将当中的凝视翻译成了中文,同一时候加入了一些自己使用经验和理解。
#include "cmdline.h"int main(int argc, char *argv[]){// 创建一个命令行解析器cmdline::parser a;// 加入指定类型的输入參数// 第一个參数:长名称// 第二个參数:短名称('\0'表示没有短名称)// 第三个參数:參数描写叙述// 第四个參数:bool值,表示该參数是否必须存在(可选。默认值是false)// 第五个參数:參数的默认值(可选,当第四个參数为false时该參数有效)a.add<string>("host", 'h', "host name", true, "");// 第六个參数用来对參数加入额外的限制// 这里端口号被限制为必须是1到65535区间的值,通过cmdline::range(1, 65535)进行限制a.add<int>("port", 'p', "port number", false, 80, cmdline::range(1, 65535));// cmdline::oneof() 能够用来限制參数的可选值a.add<string>("type", 't', "protocol type", false, "http", cmdline::oneof<string>("http", "https", "ssh", "ftp"));// 也能够定义bool值// 通过调用不带类型的add方法a.add("gzip", '\0', "gzip when transfer");// 执行解析器// 仅仅有当全部的參数都有效时他才会返回// 假设有无效參数,解析器会输出错误消息。然后退出程序// 假设有'--help'或-?
'这种帮助标识被指定,解析器输出帮助信息。然后退出程序a.parse_check(argc, argv);// 获取输入的參数值cout << a.get<string>("type") << "://"<< a.get<string>("host") << ":"<< a.get<int>("port") << endl;// bool值能够通过调用exsit()方法来推断if (a.exist("gzip")) cout << "gzip" << endl;}
使用測试
仅仅输入程序名,默认会输出帮助信息。选项后面的括号里显示了其类型和默认值(中括号)
$ ./testusage: ./test --host=string [options] ...options:-h, --host host name (string)-p, --port port number (int [=80])-t, --type protocol type (string [=http])--gzip gzip when transfer-?
, --help print this message
通过以下方式显示的输出帮助信息
$ ./test -?usage: ./test --host=string [options] ...options:-h, --host host name (string)-p, --port port number (int [=80])-t, --type protocol type (string [=http])--gzip gzip when transfer-?, --help print this message
输入必选字段--主机名,其它參数是可选的。当缺省时使用默认值,这里使用了默认协议http和默认port号80
$ ./test --host=github.comhttp://github.com:80
输入-t參数。使用ftp覆盖默认值http
$ ./test --host=github.com -t ftpftp://github.com:80
因为-t參数限制为仅仅能取cmdline::oneof<string>("http", "https", "ssh", "ftp")中的某一个。
这里输入的-t ttp不在当中,因此被视为无效參数。程序输入帮助信息然后退出。
$ ./test --host=github.com -t ttpoption value is invalid: --type=ttpusage: ./test --host=string [options] ...options:-h, --host host name (string)-p, --port port number (int [=80])-t, --type protocol type (string [=http])--gzip gzip when transfer-?, --help print this message```使用bool型參数```$ ./test --host=github.com --gziphttp://github.com:80gzip
其它选项
× footer 脚注
footer() 方法用来在帮助信息后面加入自己定义文本,比如:
a.footer("user define information...");
执行结果:
$ ./testusage: ./test --host=string [options] ...user define information...options:-h, --host host name (string)-p, --port port number (int [=80])-t, --type protocol type (string [=http])--gzip gzip when transfer-?, --help print this message
× pragram name 应用程序名
通过argv[0].set_program_name()能够设置帮助信息中的应用程序显示的名称
浙公网安备 33010602011771号