问题描述
我有一个 test.c 程序,它从标准输入中读取不同的参数,并根据给定的参数输出不同的内容。
例如:./test.c -a 1 -b 2 -c 3
所以我希望我可以根据字母去取某个功能,然后根据数字显示一些特定的东西。所以一个字母后面总是跟一个数字。
这是我的代码:
int main(int argc,char *argv[]) {
printfile();
while ((++argv)[0]) {
if (argv[0][0] == '-') {
switch (argv[0][1]) {
case 'a':
printf("case a\n"); test1(); break;
case 'b':
printf("case b\n"); test2()); break;
case 'c':
printf("case c\n"); break;
}
}
}
return 0;
}
这里我的代码只需要每个连字符后跟一个字母。是否可以将它们分开,然后将每个字母与其编号放在一起?
解决方法
通常的方法是使用 getopt()
库。
但是如果您想在代码中明确地执行此操作,您可以在 case 中增加 argv
并将下一个参数作为参数处理。
int main(int argc,char *argv[]) {
printfile();
while ((++argv)[0]) {
if (argv[0][0] == '-') {
int param;
switch (argv[0][1]) {
case 'a':
printf("case a\n");
argv++;
if (argv[0][0]) {
param = atoi(argv[0]);
test1(param);
} else {
printf("Missing argument");
exit(1);
}
break;
case 'b':
printf("case b\n");
argv++;
if (argv[0][0]) {
param = atoi(argv[0]);
test2(param);
} else {
printf("Missing argument");
exit(1);
}
break;
case 'c':
printf("case c\n");
argv++;
if (argv[0][0]) {
param = atoi(argv[0]);
test3(param);
} else {
printf("Missing argument");
exit(1);
}
break;
}
}
}
return 0;
}