gpt4 book ai didi

C getopt 多个值

转载 作者:太空狗 更新时间:2023-10-29 16:28:17 26 4
gpt4 key购买 nike

我的论点是这样的

./a.out -i file1 file2 file3

如何使用 getopt() 获取 3 个(或更多)输入文件?我正在做这样的事情:

while ((opt = getopt(argc, argv, "i:xyz.."))!= -1){
case 'i':
input = optarg;
break;
...
}

我只得到file1;如何获取file2, file3?

最佳答案

我知道这已经很老了,但我在寻找解决方案时遇到了这个问题。

while((command = getopt(argc, argv, "a:")) != -1){

switch(command){
case 'a':

(...)

optind--;
for( ;optind < argc && *argv[optind] != '-'; optind++){
DoSomething( argv[optind] );
}

break;
}

我发现 int optind(getopt() 使用的外部)指向 argv 选择的“当前 argv”之后的下一个位置em>getopt();这就是为什么我一开始就减少它。

首先 for 循环 检查当前参数的值是否在 argv 的边界内(argc 是数组的长度,所以 last数组 argv 中的位置是 argc-1)。&& 的第二部分比较下一个参数的第一个字符是否为“-”。如果第一个字符是 '-' 那么我们用完了当前参数的下一个值,否则 argv[optind] 是我们的下一个值。依此类推,直到 argv 结束或参数用完值。

在结束时递增 optind 以检查下一个 argv。

请注意,因为我们正在检查“optind < argc”,除非第一部分为真,否则不会执行条件的第一、第二部分,因此无需担心读取超出数组边界的情况。

PS 我是一个相当新的 C 程序员,如果有人有改进或批评请分享。

关于C getopt 多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3939157/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com