我一直在阅读如何使用 getopt_long()
,以及如何使用 optlong“读取”多字符选项。
我需要从终端解析以下条目:
./bomb –n String –cp Integer –i Integer –c Integer –fc String
所以在我使用 getoptlong 之前,我定义了我的短期和长期选项:
if(argc != 11){
perror("Error en numero de argumentos \n");
exit(EXIT_FAILURE);
}
const char* const short_options = "n:i:c:";
static struct option long_options[] = {
{"cp", 1, NULL, 'a'},
{"fc", 1, NULL, 'b'},
{0, 0 , 0, 0}
};
我的short_options
选择带有参数的n
(这就是:
的用途),对于c
和 i
。
因此,对于多头期权也应该应用同样的方法(它们也都接受参数)。
while(opt != -1){
opt = getopt_long(argc, argv, short_options, long_options, NULL);
switch (opt){
case 'n':
//print it
case 'a':
//print it
}
}
现在的问题是,这段代码在解析 -c -i
和 -n
时非常有效,它会输入它所属的大小写并正确打印。
我的问题是,它不适用于 -cp
和 -fc
。我真的不知道如何解决这个问题,因为我之前没有使用过 getopt()
。
提前致谢
最佳答案
引用 man getopt_long
:
The
getopt_long()
function works likegetopt()
except that it also accepts long options, started with two dashes.
和
getopt_long_only()
islike getopt_long()
, but-
as well as--
can indicate a long option.
因此您应该使用--cp
和--fc
,或者切换到getopt_long_only
。
关于C 使用 getopt_long(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14648039/