c++ - 我可以在 C++ 中使用 getopt 来读取带参数和不带参数的字符吗?

标签 c++ c++11 command-line-arguments getopt

如果用户选择 -p 而不是 -pc,我必须打印两个不同的输出。一个有论据,另一个没有论据。如果我尝试:

while( (arg = getopt_long(argc, argv, "p:")) != -1 )
{
    switch (arg)
    {
    case 'p':
        p = optarg;
        if (p=='')
            sflag = true;
        if (p=='c')
            oflag = true;        
        break;
}

然后 -pc 可以工作,但是如果我尝试 -p,我会收到一条错误消息,提示需要一个参数。如何处理 optional 参数?

最佳答案

你在使用 GNU 吗?如果是这样,你很幸运。来自docs :

The options argument is a string that specifies the option characters that are valid for this program. An option character in this string can be followed by a colon (:) to indicate that it takes a required argument. If an option character is followed by two colons (::), its argument is optional; this is a GNU extension.

因此,您需要:

while( (arg = getopt_long(argc, argv, "p::")) != -1 )

关于c++ - 我可以在 C++ 中使用 getopt 来读取带参数和不带参数的字符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35975090/

相关文章:

python - 如何将可变数量的文件作为 python 脚本的输入?

command-line-arguments - Autohotkey 脚本运行带有命令行参数的程序

c++ - 仍然遇到MD5问题

c++ - 在类中将函数作为参数传递

c++ - int 与 std::vector<int> 的重载分辨率与单个 int 的初始化列表

c++ - 在编译时检查张量是否为矩形(即多维数组的所有范围都相等)

c++ - 可以使用内联命名空间来保持共享库的向后兼容性吗?

c++ - 给定代码中是否存在未定义的行为?

c++ - 为什么我得到 "You must feed a value for placeholder tensor ' 输出 ' 与 dtype int64"?

c - 来自命令行参数的段错误(核心转储)