前文讲到了 【CommandLineParser类】opencv库中的命令行解析类,附项目应用
这里再提供一个更加方便的C++命令行解析方法
1. 定义
getopt()函数将传递给mian()函数的argc,argv作为参数,同时接受字符串参数optstring – optstring是由选项Option字母组成的字符串。
2. 格式规范
- 单个字符:该选项option不需要参数
- 单个字符后接一个冒号,表示需要一个选项参数。选项参数可以紧跟在选项option之后,也可以用空格隔开。
- 单个字符后接两个冒号,表示该选项的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;
}
}