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

标签 c++ getopt

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

-w cat



字符串“cat”存储在变量 中图案以及后面跟着 的每个字母- 我们做某事;在这种情况下,我们设置 mode = W。我遇到的问题是当参数采用以下形式时:

-w -s -n3,4 cat



现在我相信和以前一样模式按读取顺序设置为 W、S 和 N。如果我想存储/记住字母的顺序模式设置为循环完成后,我可以将信息存储在数组中。也应该做图案被分配了字符串“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设置全局变量 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对于 token (请参阅 strtok ),然后使用 atoi或类似的将每个转换为整数。

关于c++ - 在 C++ 中使用 getopt() 处理参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52467531/

相关文章:

C:读取文件而不打印同一行两次

linux - getopts : unable to identify arguments

C++ 这段代码有什么问题吗?

c++ - Boost.Program_options : Forward parameters after '--' to another program

c++ - 如何正确使用 noexcept 运算符

c++ - 错误 LNK2005 : "class Player m_player" already defined in Game. 对象

python - 如果指定用户名,为什么我的 getopts 会失败?

c - 如何使用 GETOPT 在每个命令行选项后获取指向每个参数的指针

c++ - Klocwork 9 与 Klocwork 12

c++ - 圆柱形轨迹的 3D 可视化