【问题标题】:How to parse additional arguments based on presence of another argument in getopt in c++c++ - 如何根据c ++中getopt中另一个参数的存在来解析其他参数
【发布时间】:2014-08-29 21:45:36
【问题描述】:

我需要一种方式来说明用户是否输入-f <optarg> 我需要-n <optarg>-o <optarg> 但如果用户没有指定-f,则不需要-n -o。我必须这样做类似的条件基于额外的论点解析许多案例。是否可以使用 getopt?谁能帮我做这个?

我不想在解析后检查每个变量。我希望在 getopt 字符串中可以使用任何正则表达式来完成我的工作。

【问题讨论】:

  • 解析一切,然后在最后检查你是否得到了你需要的一切?

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


【解决方案1】:

大概在您的getopt 循环中,您根据指定的标志设置了不同的变量。循环完成后,您可以轻松检查这些变量的状态。例如:

const char* someVariable = NULL;
const char* someOtherVariable = NULL;

while ((opt = getopt(argc, arv, "f:n:")) != -1)
{
    switch (opt)
    {
        case 'f':
            someVariable = optarg;
            break;
        case 'n':
            someOtherVariable = optarg;
            break;
    }
}

if (someVariable != NULL)
{
    if (someOtherVariable == NULL)
    {
        fputs("-f specified without -n", stderr);
        exit(1);
    }
}

【讨论】:

  • 是的,这就是我现在正在做的事情,但我觉得这是一种粗略的方法,我想知道是否有任何方法可以在 getopt 表达式中指定它。由于在很多情况下我都必须这样做,因此代码会因 if 循环而变得杂乱无章。
  • @VivekVK 这是你必须这样做的方式,getopt 或其他任何东西。否则你将如何处理-f ARG -n ARG -o ARG -o ARG -n ARG -f ARG?您可以检查所有选项是否仅在您完成处理所有选项之后提供。
猜你喜欢
  • 2023-03-07
  • 1970-01-01
  • 2014-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多