sta*_*low 3 c++ getopts getopt-long
#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, "svh", 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;
break;
}
}
std::cout << "GoodBye!" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
./a.out -s
Hello
You hit stuff
GoodBye!
Run Code Online (Sandbox Code Playgroud)
输出:
./a.out --stuff
Hello
./a.out: option `--stuff' requires an argument
GoodBye!
Run Code Online (Sandbox Code Playgroud)
冲突需要解决: -s和--s都应该说:./ a.out:选项`--stuff'在使用时需要一个参数,而不需要在命令之后继续执行参数.但只有 - 粮可以吗?有谁知道我在这里缺少什么?
期望的结果:
./a.out -s
Hello
./a.out: option `--stuff' requires an argument
GoodBye!
./a.out --stuff
Hello
./a.out: option `--stuff' requires an argument
GoodBye!
Run Code Online (Sandbox Code Playgroud)
小智 5
我很确定您需要将“svh”替换为“s:vh”。根据 getopt_long 的 Linux 手册页,“optstring 是包含合法选项字符的字符串。如果这样的字符后面跟着冒号,则该选项需要一个参数”。