嗨,我对编码很陌生,并试图找出为什么这个getopt不起作用。我的编译器抱怨"i:o:“
错误C2664 'int (int,char **,char *):无法将参数3从“const 5”转换为“char *”
int main(int argc, char *argv[])
{
int opt;
while ((opt = getopt(argc, argv, "i:o:")) != -1)
{
switch (opt)
{
case 'i':
printf("Input file: \"%s\"\n", optarg);
break;
case 'o':
printf("Output file: \"%s\"\n", optarg);
break;
}
}
return 0;
} 这很奇怪,因为当我读到getopt时,我看到了“options参数是一个字符串,它指定了对这个程序有效的选项字符”。
发布于 2018-04-10 17:49:54
根据您的错误消息,getopt函数需要一个可写选项字符串。您可以通过这样的非const字符数组来做到这一点:
int main(int argc, char *argv[])
{
// non-const char array
char opts[] = "i:o:"; // copy a string literal in
int opt;
while ((opt = getopt(argc, argv, opts)) != -1)
{
switch (opt)
{
case 'i':
printf("Input file: \"%s\"\n", optarg);
break;
case 'o':
printf("Output file: \"%s\"\n", optarg);
break;
}
}
return 0;
}您的原始代码在Linux和GCC v7上运行得很好。您使用的版本的函数签名似乎不同。
在my系统上,它是:
int getopt (int argc, char** argv, const char* options);但在你的系统中,它似乎是:
int getopt(int,char **,char *);在最后一个参数上缺少const会导致错误,这就是为什么您需要给它一个非const字符串。
注意:--我不建议在这方面使用const_cast,因为有些人可能会被诱惑。您永远不知道函数是如何实现的,也不知道该内部实现是否会在某一时刻发生变化。
发布于 2018-04-10 17:41:14
只需使用字符串指针:
char* opts = "i:o:";
getopt(argc, argv, opts);https://stackoverflow.com/questions/49759879
复制相似问题