使用getopt_long(C++)如何编写长短选项以都需要参数?
Using getopt_long (C++) how do I code up a long & short option to both require 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, "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;
}
输出:
./a.out -s
Hello
You hit stuff
GoodBye!
输出:
./a.out --stuff
Hello
./a.out: option `--stuff' requires an argument
GoodBye!
需要解决的冲突:-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!
您的getopt_long调用为短选项指定"svh",而它应该说"s:vh"。 冒号告诉getopt需要"s"的参数。
我很确定你需要用"s:vh"替换"svh"。 根据 Linux 手册页的getopt_long"optstring 是包含合法选项字符的字符串。如果此类字符后跟冒号,则该选项需要一个参数,"。
相关文章:
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 两个函数模板候选项.将一个参数作为引用后,选择不太专业的模板
- 提升::P设置选项无法使所有参数都处于位置状态
- 是否有 g++ 或 clang++ 调试选项来指导可变参数模板化
- C++ Catch 是否有类似 NUnit 的测试用例的东西,具有多个参数/输入选项
- C++编译时/运行时选项和参数,如何处理?
- 如何在 c/c++ 中为参数添加选项?(视觉工作室平台2019)
- 用于在 Visual Studio 中为整个项目或解决方案定义带有参数的预处理器宏的选项
- 什么是clang 选项,以便在GDB中我可以使用std :: cout作为函数参数
- 提升程序选项:参数被多次检测到
- 将参数从升压程序选项导出到doxygen
- 如何将命令行参数与c++中的选项一起传递给函数
- 是否有任何选项可以推迟对可变参数模板中函数调用的评估
- 提升program_options解析选项和参数一起
- 具有接受参数选项的默认构造函数
- 在C++中,如何仅将长选项与必需参数一起使用
- C++的任何命令行解析库是否允许具有N个参数的选项
- 具有数字偏移量的命令行参数选项
- 按位置查找未标记的模板选项/参数/参数
- 如何将值传递到qsub代码的boost选项参数中