我正在编写从命令行获取的代码。用户将在命令行中输入例如./a.out -l 2 4 6
。这里的目标是循环遍历数组,看看是否出现'-l'
或'-s'
。如果'-l'
出现,则x = 1,如果'-s'
x = 2,如果x = 0,则现在抛出的问题是第7行和第12行的指针和整数之间的比较。第12行的字符常量,我不知道为什么在第9行没问题时它会被抛出。我如何更改if
语句以修复抛出的问题?我的代码如下:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
int x;
for(; *argv != '\0'; argv++){
if(*argv == '-l'){
x = 1;
}
else if(*argv == '-s'){
x = 2;
}
else{
x = 0;
}
}
printf("%d",x);
return 0;
}
答案 0 :(得分:2)
使用双引号指定字符串,而不是用于字符的单引号。此外,您无法使用==
来比较字符串。请使用strcmp
:
if(strcmp(*argv,"-l") == 0){
...
if(strcmp(*argv,"-s") == 0){
您的输出也不会如您所愿。每次检查下一个参数时都会覆盖x
,因此结果将仅取决于最后一个参数。当满足两个条件之一时,您需要break
离开循环。
答案 1 :(得分:0)
除了其他人指出的错误之外,您可能在某些时候想要进行正确的命令行解析。在POSIX系统上,这是通过getopt()
标头中声明的unistd.h
库函数完成的(这是不是“C标准”C代码“。
我已经使用选项-x
扩展了您的需求,该选项采用一个整数参数来说明x
应该设置为:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int x = 0; /* default zero for x */
int i, tmp;
int opt;
char *endptr;
/* the ':' in the string means "the previous letter takes an argument" */
while ((opt = getopt(argc, argv, "lsx:")) != -1) {
switch (opt) {
case 'l':
x = 1;
break;
case 's':
x = 2;
break;
case 'x':
/* validate input, must be integer */
tmp = (int)strtol(optarg, &endptr, 10);
if (*optarg == '\0' || *endptr != '\0')
printf("Illegal value for x: '%s'\n", optarg);
else
x = tmp;
break;
case '?': /* fallthrough */
default:
/* call routine that outputs usage info here */
puts("Expected -s, -l or -x N");
}
}
argc -= optind; /* adjust */
argv += optind; /* adjust */
printf("x = %d\n", x);
puts("Other things on the command line:");
for (i = 0; i < argc; ++i)
printf("\t%s\n", argv[i]);
return EXIT_SUCCESS;
}
运行它:
$ ./a.out -l
x = 1
Other things on the command line:
$ ./a.out -s
x = 2
Other things on the command line:
最后一个选项“胜利”:
$ ./a.out -s -x -78
x = -78
Other things on the command line:
此处-s
是最后一次:
$ ./a.out -s -x -78 -ls
x = 2
Other things on the command line:
$ ./a.out -s -q
./a.out: illegal option -- q
Expected -s, -l or -x N
x = 2
Other things on the command line:
解析在第一个非选项停止:
$ ./a.out -s "hello world" 8 9 -x 90
x = 2
Other things on the command line:
hello world
8
9
-x
90