【发布时间】:2012-02-06 06:13:30
【问题描述】:
#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: option `--stuff' requires an argument 在不继续使用时命令后面的参数。但只有 --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!
【问题讨论】:
-
只是一点点:可能不需要那些#define语句,因为在包含getopt.h时应该将同名变量声明为枚举,因此重新定义可能会引发错误.如果某些深奥的、陈旧的或其他损坏的平台的 getopt.h 没有声明这些变量,那么 #defines 可能应该包含在 #ifdef 中,以检查仅在该特定平台上定义的某些变量。
标签: c++ getopt-long getopts