尝试使用getopt解析c中的输入
好的,基本上我是在输入a和b之后寻找一个数字,我是在不需要额外信息的情况下搜索c和d。但是,当我尝试使用getopt执行此操作时,我的循环从不执行。下面是一些示例代码:尝试使用getopt解析c中的输入,c,parsing,arguments,getopt,getopt-long,C,Parsing,Arguments,Getopt,Getopt Long,好的,基本上我是在输入a和b之后寻找一个数字,我是在不需要额外信息的情况下搜索c和d。但是,当我尝试使用getopt执行此操作时,我的循环从不执行。下面是一些示例代码: int aa = 0; int av = 0; int ab = 0; int bv = 0; int ac = 0; int cord = 0;// no c or d = 0, c = 1, d = 2 //flags and a/b value holders int getoptvalue = 0; pr
int aa = 0;
int av = 0;
int ab = 0;
int bv = 0;
int ac = 0;
int cord = 0;// no c or d = 0, c = 1, d = 2
//flags and a/b value holders
int getoptvalue = 0;
printf("starting getopt\n");
while((getoptvalue = getopt(argc,argv,"cda:b:")) != -1){
printf("inside getopt\n");
switch(getoptvalue){
case a:if(aa||ab){
exit(1);
}
else{
aa = 1;
av = atoi(optarg);//takes int value following 'a' for storage in av?
}break;
case b:if(ab){
exit(1);
}
else{
ab = 1;
bv = atoi(optarg);//takes following int value for storage?
}break;
case c:if(ac){
exit(1);
}
else{
ac = 1;//c/d switch
cord = 1; // showing c was reached
}break;
case d:if(ac){
exit(1);
}
else{
ac = 1;
cord = 2; //showing d was reached
}break;
default: break;
}
printf("done.\n");
}
编译时,此代码将打印:
$prog1 a1 b2
启动getopt
完成了
很明显,它没有运行循环,因为它从不打印“在getopt内部”,但我不明白为什么。有什么想法吗?我现在已经更改了您的代码,看起来是这样的
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc,char* argv[]) {
int aa = 0;
int av = 0;
int ab = 0;
int bv = 0;
int ac = 0;
int cord = 0;// no c or d = 0, c = 1, d = 2
//flags and a/b value holders
int getoptvalue = 0;
printf("starting getopt\n");
while((getoptvalue = getopt(argc,argv,"cda:b:")) != -1){
printf("inside getopt\n");
switch(getoptvalue){
case 'a':if(aa||ab){
exit(1);
}
else{
aa = 1;
av = atoi(optarg);//takes int value following 'a' for storage in av?
}break;
case 'b':if(ab){
exit(1);
}
else{
ab = 1;
bv = atoi(optarg);//takes following int value for storage?
}break;
case 'c':if(ac){
exit(1);
}
else{
ac = 1;//c/d switch
cord = 1; // showing c was reached
}break;
case 'd':if(ac){
exit(1);
}
else{
ac = 1;
cord = 2; //showing d was reached
}break;
default: break;
}
printf("done.\n");
}
return 0;
}
如果我遗漏了什么,我很抱歉,但是是
案例a
还是案例a'
?默认值:break代码>嗯,我不是很确定,但是您是否尝试过类似于$prog1-a1-b2
,在特定的序列中?在开关中省略默认值是一个风格问题/您与下一个家伙的意图沟通的问题。结果是输入参数。谢谢!
gcc test.c
./a.out -a a -b b
starting getopt
inside getopt
done.
inside getopt
done.
inside getopt