cmdline---C++命令行解析库

cmdline 项目托管地址:https://github.com/tanakh/cmdline

https://blog.51cto.com/u_15127663/4587654
https://www.cnblogs.com/ljbguanli/p/7235424.html

// include cmdline.h
#inclue <iostream>
#include "cmdline.h"

int main(int argc, char *argv[])
{
  // create a parser
  cmdline::parser a;

  // 第一个参数:长名称
  // 第二个参数:短名称
  // 第三个参数:参数描述
  // 第四个参数:bool值,表示该参数是否是必须存在,(可选,默认值false)
  // 第五个参数:参数的默认值,(可选,表示在第四个参数缺省下,对应参数的默认值)
  a.add<string>("host", 'h', "host name", true, "");

  // 第六个参数:限制参数的取值范围,
  a.add<int>("port", 'p', "port number", false, 80, cmdline::range(1, 65535));

  // cmdline::oneof() can restrict options.
  // cmdline::oneof() 用来限制参数的可选值,只能从限定的几个值中选取一个
  a.add<string>("type", 't', "protocol type", false, "http", cmdline::oneof<string>("http", "https", "ssh", "ftp"));

  // 通过调用不带类型的add方法,定义的bool值
  a.add("gzip", '\0', "gzip when transfer");

  // Run parser.
  // It returns only if command line arguments are valid.
  // If arguments are invalid, a parser output error msgs then exit program.
  // If help flag ('--help' or '-?') is specified, a parser output usage message then exit program.
  a.parse_check(argc, argv);

  // use flag values
  cout << a.get<string>("type") << "://"
       << a.get<string>("host") << ":"
       << a.get<int>("port") << endl;

  // boolean flags are referred by calling exist() method.
  if (a.exist("gzip")) cout << "gzip" << endl;
}
posted @ 2024-03-25 14:09  King--jin  阅读(314)  评论(0)    收藏  举报