【getopt函数】C++解析命令行选项

getopt解析命令行选项


前文讲到了 【CommandLineParser类】opencv库中的命令行解析类,附项目应用

这里再提供一个更加方便的C++命令行解析方法

1. 定义

getopt()函数将传递给mian()函数的argc,argv作为参数,同时接受字符串参数optstring – optstring是由选项Option字母组成的字符串。

2. 格式规范

  1. 单个字符:该选项option不需要参数
  2. 单个字符后接一个冒号,表示需要一个选项参数。选项参数可以紧跟在选项option之后,也可以用空格隔开。
  3. 单个字符后接两个冒号,表示该选项的option的选项参数是可选的,此时选项参数必须紧跟在选项option后面。

3. 个人项目应用

    //Variable usage of type string : use getopt to crotrol terminal command . for example ,you can use -m1 -m2 for different mode
const string usage = 
                         "Usage   :  opencv -m mode -t time -c type\r\n \
                          mode    :  algorithm mode (-1/0/1/2/3)\r\n \
                          time    :  picture time (1,2)\r\n \
                          config  :  0(default) 1(config) 2(saveconfig)\r\n \
                         ";

int mode = -1;
int config = 0; 
int time = 2;

int opt;
while ((opt = getopt(argc, (char **)argv, "m:t:c:")) != -1)
{
    switch (opt)
	{
	case 'm':
		mode = atoi(optarg);
		break;
    case 't':
        time = atoi(optarg);
        break;
    case 'c':
        config = atoi(optarg);
        break;
	case '?':
		cout << usage << endl;
		return 0;
	default:
		return 0;
    }
}
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值