在菜单中创建菜单

问题描述 投票:-1回答:1

我正在尝试在菜单中制作菜单。我的问题是“ choice”的值未更改,因此当我尝试更改选择值时,程序停止运行,例如当我首先输入(2)时,然后输入(0),而当输入(1)时,程序将终止。

#include <stdio.h>

int choice, choiceJR;

void mainMenu() {
  printf("Select one of the following. \n");  
  printf("1. x \n");
  printf("2. menuJR \n");
  printf("3. xxx \n");

  printf("Choice: \n");
  scanf("%d", &choice);
}

void menuJR() {
  printf("Select one of the following. \n");
  printf("1. y \n");
  printf("2. yy \n");
  printf("0. go back \n");

  printf("Choice: \n");
  scanf("%d", &choiceJR);

}

int main() {

  mainMenu();

  while(choice != 1 && choice!= 2 && choice!= 3) {
    printf("Invalid choice! \n");
    mainMenu();
  }
  if(choice == 1) {
    printf("You have selected 1 \n");
  }
  else if(choice == 2) {
    printf("You have selected 2 \n");
    menuJR();
    while(choiceJR != 0) {
      menuJR();
    }
    if(choiceJR == 0) {
      printf("Going to menu! \n");
      mainMenu();
    }
  }
  else if(choice == 3) {
    printf("You have selected 3 \n");
  }


  return 0;
}
c
1个回答
0
投票
  • 您应该使用do_while循环来选择项目。

  • 这是您的解决方案,请使用此代码。

    #include <stdio.h>
    
    int choiceJR=0;
    
    int mainMenu() {
        int choice=0;
        printf("Select one of the following. \n");  
        printf("1. x \n");
        printf("2. menuJR \n");
        printf("3. xxx \n");
    
        printf("Choice: \n");
        scanf("%d", &choice);
        return choice;
    }
    
    void menuJR() {
        printf("Select one of the following. \n");
        printf("1. y \n");
        printf("2. yy \n");
        printf("0. go back \n");
    
        scanf("%d", &choiceJR);
    }
    
    int main() {
        int ch=0;
    
        do {
            main:
            ch = mainMenu();
            while(ch != 1 && ch!= 2 && ch!= 3) {
                printf("Invalid choice! \n");
                mainMenu(ch);
            }
    
            switch(ch) {
                case 1:
                    printf("You have selected 1 \n");
                    break;
    
                case 2:
                    printf("You have selected 2 \n");
                    menuJR();
                    while(choiceJR != 0) {
                        menuJR();
                    }
                    if(choiceJR == 0) {
                        printf("Going to menu! \n");
                        goto main;
                    }
                    break;
    
                case 3:
                    printf("You have selected 3 \n");
                    break;
    
                default: 
                    printf("invalid choice \n");
            }
    
        }
        while(ch<=3);
    
        return 0;
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.