标签:style http io os ar 使用 for sp 文件
平时用C++写一些命令行工具,需要解析命令行的输入参数,这是一项繁琐并且容易出错的工作,我们不应该将主要精力放在这上面,可以考虑使用开源的库,下面的cmdline就是其中非常好用的一款。
cmdline 是一个非常简单好用的C++命令行解析库,其基于模板,所以使用很简单,写出的代码也很优雅。由于其只包含一个头文件,所以很容易集成到自己的项目中。
cmdline项目托管地址Github:https://github.com/tanakh/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和默认端口号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] ... filename ...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()可以设置帮助信息中的应用程序显示的名称
标签:style http io os ar 使用 for sp 文件
原文地址:http://blog.csdn.net/xiaohui_hubei/article/details/40479811