好的,基本上我正在寻找输入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;
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”,但我无法弄清楚原因。有什么想法吗?
答案 0 :(得分:0)
我已经更改了你的代码,现在它看起来像这个
#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;
}
现在,当我编译此代码并按以下方式运行时
gcc test.c
./a.out -a a -b b
starting getopt
inside getopt
done.
inside getopt
done.
inside getopt