【问题标题】:How to use nested Switch with commandline arguments?如何使用带有命令行参数的嵌套 Switch?
【发布时间】:2018-04-06 15:06:47
【问题描述】:

我的主函数中有我的 switch 案例和语句,如下所示:

int main(int argc, char *argv[])
{
  int c;
  while((c = getopt(argc,argv,"ABS"))!=-1)
    {
      switch(c)
      {
        case 'A':
         flag = 0;
         printf("open the port\n");
         struct can_frame frame_rd;
         open_port("vcan0");
         printf("vcan0 port is opened");
         fflush(stdout);
         create_file();
         while(1)
         {
           read_port(&frame_rd);
         }
         break;
       case 'B':
        flag = 1;
         printf("open the port\n");
         open_port("vcan0");
         printf("vcan0 port is opened");
         fflush(stdout);
         create_binfile();
         while(1)
         {
           read_port(&frame_rd);
         }
         break;
      }
}

现在我想在用户在case A 中传递参数 -S 时使用嵌套开关,我可以按以下方式执行吗?下面的步骤正确吗?

int main(int argc, char *argv[])
{
  int c;
  while((c = getopt(argc,argv,"ABS"))!=-1)
    {
      switch(c)
      {
        case 'A':

          switch(c)
           {
             case 'S':
               size = 100;
               break;
           }
         flag = 0;
         printf("open the port\n");
         struct can_frame frame_rd;
         open_port("vcan0");
         printf("vcan0 port is opened");
         fflush(stdout);
         create_file();
         while(1)
         {
           read_port(&frame_rd);
         }
         break;
       case 'B':
        flag = 1;
         printf("open the port\n");
         open_port("vcan0");
         printf("vcan0 port is opened");
         fflush(stdout);
         create_binfile();
         while(1)
         {
           read_port(&frame_rd);
         }
         break;
      }
}

在上面的代码中,我也可以将相同的switch(c) 用于嵌套情况吗,嵌套开关的使用是否正确?提前谢谢。

【问题讨论】:

    标签: c switch-statement case


    【解决方案1】:

    不,在外部 swich case 'A' 中,变量 c 可以被认为是常量,因此您的嵌套 switch 将找不到匹配的 case 并且没有默认 case。

    如果您知道您的论点按特定顺序排列,您可以直接解决它们,例如argv[1] 和 argv[2] 用于第一个和第二个参数。

    【讨论】:

    • 如果我接受int i,我如何在while循环中给出i = getopt(argc,argv, "ABS")?我想在我的case A 中使用switch(i)。有可能吗?
    • 哦...那我必须这样做.. 否则使用.. if argv[2]==S { size = 100 ; } else { size = 1000; } 然后是我的case A
    • @sp5 是的,只要您的论点保持有序。有很多关于传递命令行开关参数以及如何以任意顺序解析它们的教程。它通常循环遍历 argv 数组并为每个参数做一些事情;参数之间存在依赖关系可能是糟糕的设计。
    猜你喜欢
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多