sta*_*low 4 c++ parsing getopt-long command-line-arguments
#include <iostream>
#include <getopt.h>
#define no_argument 0
#define required_argument 1
#define optional_argument 2
int main(int argc, char * argv[])
{
std::cout << "Hello" << std::endl;
const struct option longopts[] =
{
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{"stuff", required_argument, 0, 's'},
{0,0,0,0},
};
int index;
int iarg=0;
//turn off getopt error message
opterr=1;
while(iarg != -1)
{
iarg = getopt_long(argc, argv, "s:vh", longopts, &index);
switch (iarg)
{
case 'h':
std::cout << "You hit help" << std::endl;
break;
case 'v':
std::cout << "You hit version" << std::endl;
break;
case 's':
std::cout << "You hit stuff" << std::endl;
if(optarg)
std::cout << "Your argument(s): " << optarg << std::endl;
break;
}
}
std::cout << "GoodBye!" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
期望的输出:
./a.out --stuff someArg1 someArg2
Hello
You hit stuff
Your agument(s): someArg1 someArg2
GoodBye!
Run Code Online (Sandbox Code Playgroud)
当处理完所有选项时,getopt返回-1 .在--stuff
被公认为是需要一个参数,在这种情况下的一个选项someArg1
.该someArg2
ARG不启动-
或--
,所以它不是一个选项.默认情况下,这将被置换到最后argv
.之后的getopt返回-1,所有非选项ARGS将是argv
来自optind
于argc-1
:
while (iarg != -1) {
iarg = getopt_long(argc, argv, "s:vh", longopts, &index);
// ...
}
for (int i = optind; i < argc; i++) {
cout << "non-option arg: " << argv[i] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
如果-
在开头添加单个optstring
,getopt
则返回1(不是'1')并指向optarg
非选项参数:
while (iarg != -1) {
iarg = getopt_long(argc, argv, "-s:vh", longopts, &index);
switch (iarg)
{
// ...
case 1:
std::cout << "You hit a non-option arg:" << optarg << std::endl;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6804 次 |
最近记录: |