getopt 给出 -1 作为返回值
我想看看 getopts 是如何工作的。我写了下面的代码,但不确定我做错了什么。请指出我:
#include<unistd.h>
..
..
int main( int argc, char *argv[])
{
int ch=0;
while((ch=getopt(argc, argv, "ltR:")!=-1) // 0 here was by mistake. Changed to -1
{
printf("%d",ch); //This prints -1
switch(ch)
{
case 'l':
printf("l");
break;
case 't':
printf("t");
break;
case 'R':
printf("R");
break;
}
}
return 0;
}
$ ./a.out -ltR
$ -1
$ ./a.out -l
$ -1
可能我犯了一个真正的错误,或者错过了我对 getopt 理解的某些方面。
进行了更改,但仍然给出相同的结果:(
谢谢, 费赞
I am trying to see how getopts work. I wrote the code below but not sure what I am doing wrong. Please point me :
#include<unistd.h>
..
..
int main( int argc, char *argv[])
{
int ch=0;
while((ch=getopt(argc, argv, "ltR:")!=-1) // 0 here was by mistake. Changed to -1
{
printf("%d",ch); //This prints -1
switch(ch)
{
case 'l':
printf("l");
break;
case 't':
printf("t");
break;
case 'R':
printf("R");
break;
}
}
return 0;
}
$ ./a.out -ltR
$ -1
$ ./a.out -l
$ -1
May be I am doing a really mistake or missing out on some aspect of my understanding of getopt.
Made changes but still gives the same result:(
Thanks,
Faizan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你的 while 表达式应该是,
并且如果 switch 是可选的,选项应该以 ':'
或两个 ':' 结尾。
I think your while expression should be
and the option should end with ':'
or two ':' if switch is optional.
从手册页来看,-1 表示所有参数都已完成,而不是您似乎正在检查的 0。
您问题中的代码无法立即解析,因此它似乎不是正确的复制粘贴,这使得发现错误变得更加困难。 while 循环上的括号可能是导致问题的原因,但很难说。如果我复制粘贴您的示例并更正括号问题,代码将按您的预期工作。
From the man page -1 indicates that all the arguments have been done, rather than 0 as you appear to be checking for.
The code in your question doesn't parse out of the box so it doesn't appear to be a proper copy paste which makes spotting the error a lot harder. The brackets on the while loop might be the cause of your issue but it's hard to tell. If I copy paste your example and correct the bracket issue the code works as you expect it to.