c - 如何计算 C 中的 argc

标签 c arguments parameter-passing argv argc

我在获取正确数量的参数时遇到问题:

    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. Then optind is the index in argv of the first argv-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/

相关文章:

c - 什么是 Antlr3 C 运行时等效于抛出错误报告的异常

c - 编写编译器时,如何检查标记?

python - 函数参数 - 两种输入方法之间的差异

c# - 为一个对象分配多个值(?)

c++ - 在 C++ 中访问参数包的内部变量

C: 下面的代码无法编译?

java - 在 Java 中处理 Not Acceptable 方法参数的最佳方法是什么?

java - 如何在 JSF 2 的值表达式和方法表达式中传递参数?

C++ - 将函数设置为等于参数

ios - 用C语言将数组数据设置为Avro数组类型