【问题标题】:Choose an option with switch-case and go back to menu (C)选择带开关盒的选项并返回菜单 (C)
【发布时间】:2020-05-06 12:31:21
【问题描述】:

我有这个代码例如:

   void example()  {
   int i,j,k;
   int sum = 0;
   int a;
   printf("Menu");
   printf("Enter 1 for first case or 0 to exit");
   scanf("%d" , &a);

switch(a){
    case 1:
        printf("first case");
        printf("now go back to Menu");
        break;}

case 0:
    exit(0);

    break;}

我想知道如果我选择第一种情况,我如何每次回到:

printf("Menu"); 

我不想调用 example() 函数,我只想进入这个特定的行。

我可以用 switch-case 语句或其他东西来做到这一点吗?

【问题讨论】:

    标签: c loops if-statement switch-statement


    【解决方案1】:

    使用循环:

    while(1) {
       printf("Menu");
       printf("Enter 1 for first case or 0 to exit");
       scanf("%d" , &a);
    
       switch(a){
        case 1:
            printf("first case");
            printf("now go back to Menu");
            break;
    
        case 0:
            exit(0);
        }
    
        default:
            break;
    }
    

    旁注:

    1. a 既不是10 时,您应该添加default 标记。

    2. 如果您想要不同屏幕的错觉,您还需要使用 f.e. 清除当前屏幕。 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");.

    3. 如果唯一的输入是10if/else 将比switch 语句更合适。

    例如:

    while(1) {
       printf("Menu");
       printf("Enter 1 for first case or 0 to exit");
       scanf("%d" , &a);
    
       if(a == 1) {
            printf("first case");
            printf("now go back to Menu");
            break;
        }
        else if(a == 0) {
            exit(0);
        }
    
        printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    }
    

    甚至更简单:

    while(1) {
       printf("Menu");
       printf("Enter 1 for first case or 0 to exit");
       scanf("%d" , &a);
    
       if(a == 0) {
            exit(0);
        }
    
        printf("first case");
        printf("now go back to Menu");
    
        printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-13
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      相关资源
      最近更新 更多