getopt()@unistd.h
在Linux系统的unistd.h库中包含getopt()函数,很好用。
函数原型:
int getopt( int argc, char *const argv[], const char *optstring );
如果不再有识别到的选项时,函数将返回 -1,参数解读就完成了。
需要特别说明的第三个参数,eg: “a:bc”表示有一个带参的选项a,两个不带参的选项b和c
#include<stdio.h>
#include<unistd.h>
int main(int argc, char** argv)
{
int ch;
opterr = 0;
while((ch = getopt(argc, argv, "p:d:")) != -1)
switch(ch)
{
case 'p':
printf("path='%s'\n", optarg); break;
case 'd':
printf("dest:%s\n",optarg); break;
default:
printf("other option :%c\n", ch);
}
printf("optopt +%c\n", optopt);
}
骚气的写法查考([1]:使用 getopt() 进行命令行处理)
parg ——a getopt() implement
getopt()并不是标准C的一部分,有时候引用不到unistd库,github上有很多童鞋自己实现了类似功能的函数,这里挑一个比较接近getopt()又比较方便的实现[2]
demo
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include "parg.h"
using namespace std;
using std::string;
int main(int argc, char *argv[])
{
struct parg_state ps;
int ch;
parg_init(&ps);
while ((ch = parg_getopt(&ps, argc, argv, "p:d:h")) != -1)
{
switch (ch)
{
case 'p':
cout << "path:" << ps.optarg << endl;
break;
default:
break;
}
}
}
cv::CommandLineParser Class@opencv
http://docs.opencv.org/3.3.0/d0/d2e/classcv_1_1CommandLineParser.html
简直不能更好用
int main(int argc, char *argv[])
{
const String keys = {
"{help h usage ? | | print this message }"
"{@image | | image1 for compare }"
};
cv::CommandLineParser parser(argc, argv, keys);// "{help h||}{@input||}");
if (parser.has("help"))
{
parser.printMessage();
return 0;
}
string filepath = parser.get<string>("@image");
if (filepath.empty())
cin >> filepath;
else
;
//use filepath
return 0;
}