[C++] cmdline 轻量的命令行解析库
1.0 简述
tanakh/cmdline
1415 更新于2020-12-13 18:12:48
在使用 C++ 写命令行工具的时候,需要解析输入的参数,该库就是为这一解析工作提供一个方便快捷的方案。
2.0 使用
该项目仅包含一个头文件 include "cmdline.h"
以下是一个简单示例
#include <iostream>
#include "cmdline/cmdline.h"
int main(int argc, char *argv[]){
/* 创建一个命令解析器 */
cmdline::parser options;
/* 1op -> 长名称
* 2op -> 短名称 / 如果没有短名写 '\0'
* 3op -> 解释
* 4op -> 是否必填
* 5op -> 默认值,仅在 4op 为 false 的时候生效
*/
options.add<std::string>(
"host",
'h',
"host name",
true,
"");
// range -> 可以用于限制输入值范围
options.add<int>(
"port",
'p',
"port number",
false,
80,
cmdline::range(1, 65535));
// oneof 限制参数的可选值
options.add<std::string>(
"type",
't',
"protocol type",
false,
"http",
cmdline::oneof<std::string>("http", "https", "ssh", "ftp"));
// 可以定义 bool 值
options.add("gzip", '\0', "gzip when transfer");
/* 执行解析器 */
options.parse_check(argc, argv);
std::cout << "input type -> " << options.get<std::string>("type") << std::endl;
std::cout << "input host -> " << options.get<std::string>("host") << std::endl;
std::cout << "input port -> " << options.get<int>("port") << std::endl;
// bool 值仅能通过 exist() 方法判断
if (options.exist("gzip")){
std::cout << "gzip enable" << std::endl;
}else{
std::cout << "gzip disable" << std::endl;
}
return 0;
}
传入定义好的参数即可看到效果
可以输出帮助消息
END 参考与引用
[参考文章]
评论区(暂无评论)