我在获取正确数量的参数时遇到问题:
while((opt=getopt(argc, argv, ":a:c:SL")) != -1)
如果我启动脚本:
./script -a ok -c 1 -S -L
argc 变量等于 7
问题 是当我想将脚本作为 ./script -a ok -c 1 -SS -L
argc 变量等于 7 时,但它应该是 8,因为(SS(或 LL/CC)需要算作两个)。
最佳答案
这听起来像 XY problem .我怀疑您想要计算 getopt
处理的参数数量的原因是为了访问任何以下不是选项的参数。
man page指向解决方案:
If there are no more option characters,
getopt()
returns -1. Thenoptind
is the index inargv
of the firstargv
-element that is not an option.
while
循环完成后,您可以执行以下操作:
int i;
for (i = optind; i < argc; i++) {
printf("non-option arument: %s\n", argv[i]);
}
或者,您可以向上移动 argv
使其指向第一个非选项参数,并相应地减少 argc
。然后就可以从0开始索引了:
argc -= optind;
argv += optind;
int i;
for (i = 0; i < argc; i++) {
printf("non-option arument: %s\n", argv[i]);
}
关于c - 如何计算 C 中的 argc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47073340/