Playing around with getopt
Playing around with getopt
嗨,我对编码很陌生,并试图找到为什么这个getOpt不起作用。 我的编译器抱怨"I:O:">
错误 C2664 'int getopt(int,char **,char *(':无法将参数 3 从"const char [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的信息时,我看到了这个"选项参数是一个字符串,指定对此程序有效的选项字符。
根据您的错误消息,getopt
函数需要一个可写的选项字符串。你可以通过创建一个非常量字符数组来做到这一点,如下所示:
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;
}
您的原始代码在与GCC v7
Linux
上对我来说效果很好.您正在使用的版本的功能签名似乎不同。
在我的系统上是:
int getopt (int argc, char** argv, const char* options);
但是在您的系统上,它似乎是:
int getopt(int,char **,char *);
最后一个参数缺乏const
会导致错误,这就是为什么您需要给它一个非常量字符串的原因。
注意:我不建议为此使用const_cast
,因为有些人可能会受到诱惑。你永远不知道函数是如何实现的,或者内部实现是否会在某个时候发生变化。
只需使用字符串指针:
char* opts = "i:o:";
getopt(argc, argv, opts);
相关文章:
- Problems with std::cin.fail()
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 这对"With a stackless coroutine, only the top-level routine may be suspended."意味着什么
- Boost.TEST with CLion: "Test framework quit unexpectedly"
- 避免碎片化的ClientHellos with OpenSSL (DTLS)
- Issues with Win32 ReadProcessMemory API
- Qt with WinAPI MouseProc
- [[maybe_unused]] with structured_binding?
- Issue with WriteProcessMemory
- OpenCV RTP-Stream with FFMPEG
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- std::adjacent_difference with std::chrono time_point
- DLL Made with CMake 使程序崩溃
- QtCreator with C 库中的链接器问题
- SHBrowseForFolder with BIF_BROWSEFORCOMPUTER and SHGetPathFr
- specialized std::default_delete with QQmlComponent
- VS2019 - Sudo Remote Debugging on Linux with Cmake project
- Inference pytorch C++ with alexnet and cv::imread image
- atof coredump with getopt
- Playing around with getopt