否则如果声明结束程序

时间:2017-04-02 01:45:49

标签: c function if-statement

我试图编写一个函数yes,确认用户是否要退出该程序。如果用户输入“Y”或“y”它会成功退出,如果用户输入无效输入,它也会成功退出,但是,如果用户输入“N”或“n”,它将返回菜单,但任何进一步输入只会结束程序。我也尝试过while while循环,但遇到了类似的问题。这是我的代码:

void GroceryInventorySystem(void) {
    int menuSelection;
    int exitSelection;

    welcome();
    printf("\n");

    while (menuSelection != 0)
    {
        menuSelection = menu();
        switch (menuSelection)
    {
        case 1:
        printf("List Items under construction!\n");
        pause();
        break;

        case 2:
        printf("Search Items under construction!\n");
        pause();
        break;

        case 3:
        printf("Checkout Item under construction!\n");
        pause();
        break;

        case 4:
        printf("Stock Item under construction!\n");
        pause();
        break;

        case 5:
        printf("Add/Update Item under construction!\n");
        pause();
        break;

        case 6:
        printf("Delete Item under construction!\n");
        pause();
        break;

        case 7:
        printf("Search by name under construction!\n");
        pause();
        break;

        default:
        printf("Exit the program? (Y)es/(N)o: ");
        exitSelection = yes();
        break;
        }
    }
}

int yes(void) {
        char YN;
        begin:;

        scanf("%c", &YN);
        flushKeyboard();

        if (YN == 'Y' || YN == 'y') {
        }

        else if (YN == 'N' || YN == 'n') {
        menu();
        }   

        else {
            printf("Only (Y)es or (N)o are acceptable: ");
            goto begin;
        }           
}

int menu(void) {
    int option;
    int firstSelection = 0;
    int lastSelection = 7;
    printf("\n1- List all items\n");
    printf("2- Search by SKU\n");
    printf("3- Checkout an item\n");
    printf("4- Stock an item\n");
    printf("5- Add new item or update item\n");
    printf("6- Delete item\n");
    printf("7- Search by name\n");
    printf("0- Exit program\n");
    printf("> ");
    option = getIntLimited(firstSelection, lastSelection);
    return option;
}

如有必要,我可以提供其余的代码。

2 个答案:

答案 0 :(得分:1)

查看代码的作用,这是程序运行时有人选择菜单选项' 0':

  • menu()返回0并被分配到menuselection
  • 执行退出案例并运行yes()
  • 此处用户选择'N'并再次调用menu()
  • menu()返回选择的任何选项,并且不执行任何操作
  • run()到达执行结束的行为为undefined
  • while循环结束并再次执行,menuselection仍为0

当您执行退出案例时,您需要向您的while循环发出信号,告知用户已经改变了主意。

答案 1 :(得分:0)

int yes(void) 
{
            char YN;
            begin:;

            scanf("%c", &YN);
            flushKeyboard();

            if (YN == 'N' || YN == 'n') {
                    return 0;
            }

            else if (YN == 'Y' || YN == 'y') {
                    printf("Goodbye!\n");
            }

            else {
                    printf("Only (Y)es or (N)o are acceptable: ");
                    goto begin;
            }
}