小标
2018-12-14
来源 :
阅读 2083
评论 0
摘要:本文主要向大家介绍了 C/C++知识点之【C++】cmdline —— 轻量级的C++命令行解析库,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
本文主要向大家介绍了 C/C++知识点之【C++】cmdline —— 轻量级的C++命令行解析库,通过具体的内容向大家展示,希望对大家学习C/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
使用測试
仅仅输入程序名,默认会输出帮助信息。选项后面的括号里显示了其类型和默认值(中括号)
$ ./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.com//github.com:80
输入-t參数。使用ftp覆盖默认值http
$ ./test --host=github.com -t ftpftp://github.com:80
因为-t參数限制为仅仅能取cmdline::oneof
$ ./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 --gzip//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()能够设置帮助信息中的应用程序显示的名称
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C/C+频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号