【问题标题】:Get several values for the same option [duplicate]为同一选项获取多个值[重复]
【发布时间】:2013-07-02 14:20:23
【问题描述】:

我有一个这样的程序:

./server

哪个有这个用法:

Usage : 
-p  Port to use (4242 by default)
-x  Map width (20)
-y  Map height (20)
-n  Team name (name_team1 name_team2)
-c  Players per team
-t  Delay 

我能够用这段代码解析所有选项:

int parse_cmd(int argc, char **argv, t_args *a)
{
    char ch;

    if (argv[1] && argv[1][0] != '-')
        usage();
    while ((ch = getopt(argc, argv, "p:x:y:n:c:t:")) != -1)
    {
        if (ch == 'p')
            a->port = atoi(optarg);
        else if (ch == 'x')
            a->x = atoi(optarg);
        else if (ch == 'y')
            a->y = atoi(optarg);
        else if (ch == 'n')
            a->teams = name_teams(optarg);
        else if (ch == 'c')
            a->size = atoi(optarg);
        else if (ch == 't')
            a->delay = atoi(optarg);
        else
            usage();
    }
    if (check_values(a) == FALSE)
        return (FALSE);
    return (TRUE);
}

但问题是,对于-n 选项,我必须得到这样的团队名称:

./server -n team1 team2 team2

我就是无法改变现状。

显然我可以做到:

./server -n "team1 team2 team3"

并解析团队,但这是针对我的公司的,他们不想在团队名称周围加上引号,不要问我为什么...

在不使用 shell 引号的情况下如何获取所有团队名称的任何帮助?

【问题讨论】:

    标签: c getopt


    【解决方案1】:

    我认为你有三种不同的可能性:

    1. 使用多个'-n'参数:

      ./server -n team1 -n team2 -n team3
      
    2. 在 optarg 中使用像 ',' 这样的字符作为分隔符

      ./server -n team1,team2,team3
      
    3. 不要使用 getopt,而是自己解析 argv

    【讨论】:

      【解决方案2】:

      您也可以使用optindoptint 跟踪遇到的选项数量。 optind 指向argv[]getopt() 遇到的下一个索引

      因此您可以在argv 中查找是否有团队。但要使其正常工作,您应该在下一个片段"p:x:y:nc:t:" 中省略 optstring 中的“:”,或者在循环中使用 optint 之前减少它的值。

      这只是一个判断循环是否必须继续的简单函数。

      int 
      is_team ( const char* team ) {
          if ( team == NULL)
              return 0;
          else if ( team[0] == '-' ) /*new argument*/
              return 0;
          else
              return 1;
      }
      

      这就是你遇到'n'选项时所做的事情,你也可以在optstring中使用冒号,但是遇到选项也会被计算在内,然后i = optind - 1也可能会起作用

      case 'n':
          { /*note this scope is significant*/
              int i;
              for ( i = optind ; is_team(argv[i]); ++i  ) {
                  printf ( "team = %s\n", argv[i]);
                  //argument = ++*optarg;
              }
          }
          break;
      

      我希望这会有所帮助。

      【讨论】:

      • 成功了!谢谢!
      【解决方案3】:

      else if (ch == 'n') 分支中使用getopt 解析所有团队,直到出现下一个选项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-10
        • 2014-12-26
        • 1970-01-01
        • 2014-04-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多