【问题标题】:Using getopt() in C++ to handle arguments在 C++ 中使用 getopt() 处理参数
【发布时间】:2018-09-23 15:21:57
【问题描述】:

程序是这样工作的,参数在开头以这样的形式提供:

-w 猫

字符串“cat”存储在变量pattern中,对于后面跟着-的每个字母我们做一些事情;在这种情况下,我们设置 mode = W。我遇到的问题是参数的格式为:

-w -s -n3,4 猫

现在我相信 mode 按照读取的顺序设置为 W、S 和 N。如果我想在循环完成后存储/记住字母 mode 的顺序,我可以将信息存储在一个数组中。同样应该为 pattern 分配字符串“cat”。如果我错了,请纠正我或者有更简单的方法来做到这一点。

其次,我希望能够访问和存储数字 3 和 4。我不确定这是如何完成的,也不确定是什么 argc -= optind;和 argv += optind;做。除了我认为参数存储在字符串数组中。

enum MODE {
    W,S,N
} mode = W;
int c;
while ((c = getopt(argc, argv, ":wsn")) != -1) {
    switch (c) {
        case 'w': 
            mode = W;
            break;
        case 's': 
            mode = S;
            break;
        case 'n':
            mode = N;
            break;   
    }
}
argc -= optind; 
argv += optind; 

string pattern = argv[0];

更新:想出了如何访问数字,我只需要查看循环期间 argv 中的内容。所以我想我会将在那里找到的值存储在另一个变量中以供使用。

【问题讨论】:

  • 我可以推荐getopt_long,或者更好的是boost::program_options
  • 还可以看看这个名为 Clara.. 的库,它看起来很酷!
  • 谢谢,但我必须使用 getopt :(

标签: c++ getopt


【解决方案1】:

getopt 在提供带值的参数时设置全局变量optarg。例如:

for(;;)
{
  switch(getopt(argc, argv, "ab:h")) // note the colon (:) to indicate that 'b' has a parameter and is not a switch
  {
    case 'a':
      printf("switch 'a' specified\n");
      continue;

    case 'b':
      printf("parameter 'b' specified with the value %s\n", optarg);
      continue;

    case '?':
    case 'h':
    default :
      printf("Help/Usage Example\n");
      break;

    case -1:
      break;
  }

  break;
}

有关更完整的示例,请参阅 here

我希望能够访问和存储数字 3 和 4。

由于这是一个逗号分隔的列表,您需要解析optarg 的标记(请参阅strtok),然后使用atoi 或类似方法将每个标记转换为整数。

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2018-05-24
    • 2018-01-03
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多