在 C++ 中使用 getopt() 来处理参数

Using getopt() in C++ to handle arguments

程序是这样运行的,参数在开始时以这样的形式提供:

-w cat

字符串 "cat" 存储在变量 pattern 中,对于后跟 - 的每个字母,我们做一些事情;在这种情况下,我们设置 mode = W。我遇到的麻烦是当参数采用以下形式时:

-w -s -n3,4 cat

现在我相信和以前一样 mode 设置为 W、S 和 N,顺序是读取。如果我想 store/remember 在循环完成后将字母 mode 的顺序设置为什么,我可以将信息存储在数组中。同样应该做的是 pattern 被分配了字符串 "cat"。如果我错了或有更简单的方法来纠正我。

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

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 在提供具有值的参数时设置全局变量 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

I want to be able to access and store the numbers 3 and 4.

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