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++ 特定语法

c# - 如何在C#中传递参数rowIndex

c++ - 如何在不复制的情况下使用 std::string?

c++ - curl_easy_perform() 失败 : failed FTP upload (the STOR command) error

c - Linux DMA : Using the DMAengine for scatter-gather transactions

c - 删除数组中元素的函数如何工作?

linux - 在命令行中传递 unix 中的参数

javascript - 如何在函数调用中指定(默认)参数而不使用 undefined

powershell - 如何从TeamCity构建配置中设置PowerShell开关参数

c++ - 如何获取打印机状态?