gpt4 book ai didi

c - 在菜单中制作菜单

转载 作者:行者123 更新时间:2023-11-30 14:34:32 27 4
gpt4 key购买 nike

我正在尝试在菜单中制作菜单。我的问题是“选择”的值没有改变,因此当我试图改变选择的值时程序停止,例如当我输入(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;
}

最佳答案

  • 您应该使用 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;
    }

关于c - 在菜单中制作菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58930828/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com