我正在调用一个简单的可执行文件:
$ ./test -l 123
我有一些相对简单的代码,用于检查是否提供了足够的args,如果没有提示用户输入值。
代码如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int main(int argc, char *argv[])
{
long max_number;
char out[1024];
// Check whether max_number was passed via args
if (argc < 2) {
printf("Enter the maximum number: ");
fflush(stdout);
scanf("%d", &max_number);
} else {
for (int i=1; i<argc; i++) {
sprintf(out, "%sArg %d of %d is '%s'\n", out, i, argc, argv[i]);
if (strcmp(argv[i], "-l") && argc > i) {
sprintf(out, "%sFound '-l' argument at index %d\n", out, i);
int argTarget = i + 1;
sprintf(out, "%sLooking for the maximum number at argument %d\n", out, argTarget);
max_number = atoi(argv[argTarget]);
}
}
}
printf("%s", out);
printf("Maximum number received: %d\n", max_number);
return 0;
}
我期望从上面的命令得到的是:
Arg 1 of 3 is '-l'
Arg 2 of 3 is '123'
Found '-l' argument at index 1
Looking for the maximum number at argument 2
Maximum number received: 123
实际发生的是:
Arg 1 of 3 is '-l'
Arg 2 of 3 is '123'
Found '-l' argument at index 2
Looking for the maximum number at argument 3
Maximum number received: 0
所以出于某种原因,尽管事实上我可以从索引i
获取值没有问题,但当我尝试获取i
的值时,它似乎比它应该高一个是。当我在for
循环的第一行检查它时,我不明白为什么它是正确的,但是当我在strcomp()
之后检查它似乎是不正确的。
有谁能帮我理解这里发生了什么?
我在Windows 10上使用GCC并在MinGW-64终端中运行。要编译,我只是在运行:
$ gcc args.c -o args
答案 0 :(得分:3)
strcmp
会返回0
。因此:
if (strcmp(argv[i], "-l") && argc > i) {
应该是:
if (strcmp(argv[i], "-l") == 0 && argc > i) {
另请注意,代码还存在一些其他问题:
strings.h
应为string.h
out
- 将其删除并改为使用printf
。您目前正在打破别名,因为您将out
传递给sprintf
的输出和输入。printf
格式字符串。尝试在启用完整警告的情况下编译代码!这是没有警告的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int max_number;
// Check whether max_number was passed via args
if (argc < 2) {
printf("Enter the maximum number: ");
fflush(stdout);
scanf("%d", &max_number);
} else {
for (int i=1; i<argc; i++) {
printf("Arg %d of %d is '%s'\n", i, argc, argv[i]);
if (strcmp(argv[i], "-l") == 0 && argc > i) {
printf("Found '-l' argument at index %d\n", i);
int argTarget = i + 1;
printf("Looking for the maximum number at argument %d\n", argTarget);
max_number = atoi(argv[argTarget]);
}
}
}
printf("Maximum number received: %d\n", max_number);
return 0;
}