除了其他人指出的错误之外,您可能在某些时候想要进行正确的命令行解析。在 POSIX 系统上,这是通过在 unistd.h 标头中声明的 getopt() 库函数完成的(这不是“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