问题描述
我有一个使用各种命令行参数的程序。为了简化起见,我们将说它带有3个标志,分别为 -a
, -b
和 -c
,并使用以下代码解析我的参数:
I have a program which takes various command line arguments. For the sake of simplification, we will say it takes 3 flags, -a
, -b
, and -c
, and use the following code to parse my arguments:
int c;
while((c = getopt(argc, argv, ":a:b:c")) != EOF)
{
switch (c)
{
case 'a':
cout << optarg << endl;
break;
case 'b':
cout << optarg << endl;
break;
case ':':
cerr << "Missing option." << endl;
exit(1);
break;
}
}
注意:a和b在标志后取参数。
note: a, and b take parameters after the flag.
但是我调用程序时遇到问题
But I run into an issue if I invoke my program say with
./myprog -a -b parameterForB
其中我忘记了parameterForA,parameterForA(由optarg)返回为 -b
,parameterForB被视为不带参数的选项,并且optind设置为argv中parameterForB的索引。
where I forgot parameterForA, the parameterForA (represented by optarg) is returned as -b
and parameterForB is considered an option with no parameter and optind is set to the index of parameterForB in argv.
在这种情况下,所需的行为是在未找到 -a ':'
c $ c>和 Missing选项。
打印为标准错误。但是,只有在 -a
是传递到程序中的最后一个参数的情况下,才会发生这种情况。
The desired behavior in this situation would be that ':'
is returned after no argument is found for -a
, and Missing option.
is printed to standard error. However, that only occurs in the event that -a
is the last parameter passed into the program.
我猜问题是:是否有一种方法可以使 getopt()
假定没有选项将以-
开头?
I guess the question is: is there a way to make getopt()
assume that no options will begin with -
?
推荐答案
请参见。它说,
See the POSIX standard definition for getopt
. It says that
对于该检测,
- 如果该选项是
指向字符串中argv元素的最后一个字符,则optarg应将
包含argv的下一个元素,并且
optind应加2。如果
optind的结果值比argc大
,这表明缺少
的期权参数,而getopt()
将返回错误指示。 - 否则,optarg将指向argv该元素中选项
字符后的字符串,并且
optind应加1。
看起来像 getop t
被定义为不执行您想要的操作,因此您必须自己实施检查。幸运的是,您可以通过检查 * optarg
并自己更改 optind
来做到这一点。
It looks like getopt
is defined not to do what you want, so you have to implement the check yourself. Fortunately, you can do that by inspecting *optarg
and changing optind
yourself.
int c, prev_ind;
while(prev_ind = optind, (c = getopt(argc, argv, ":a:b:c")) != EOF)
{
if ( optind == prev_ind + 2 && *optarg == '-' ) {
c = ':';
-- optind;
}
switch ( …
这篇关于getopt无法检测到选项的缺少参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!