首页 > 解决方案 > 使用 Do while 循环和 Switch 语句在 C 中测试输入的问题

问题描述

因此,我在通过作业验证输入时遇到了很多麻烦,我尝试使用 do while 循环来针对四个字符测试输入的有效性以及 switch 语句,但无论我做什么,我都会陷入无限循环或代码中断并且根本不输出任何内容,无论我输入什么,我都会在 Ubuntu 中冻结。这是我尝试过的两种不同的方法,但都没有成功。对于那些好奇的人,我的任务是重新制作扫雷,我的教授为我们把它分成了 3 个部分。感谢您提前提供任何帮助!(完整代码https://pastebin.com/QCT74x4g

int acceptInput()
{
    int row;
    int column;
    char menu;
    printf("____________________________MENU____________________________\n");

    printf("(F) flag a spot as a mine, (R) remove a flag, (A) assert that spot is mine free, (Q) quit the game\n");
    scanf("%c", &menu);
    getchar();
    menu = toupper(menu);
    printf("input: %c", menu);

    switch(menu)
    {
    case 'F':
    {
        printf("Input successfully entered as F!");
        break;
    }
    case 'R':
    {
        printf("Input successfully entered as R!");
        break;
    }
    case 'A':
    {
        printf("Input successfully entered as A!");

        break;
    }
    case 'Q':
    {
        printf("Input successfully entered as Q!");

        tearDown();
        break;
    }
    default:
    {
        printf("Bad input, Try again.\n");
        acceptInput();
    }
    }

    printf("input successful4");
}


//method 2
int acceptInput()
{
    int row;
    int column;
    char menu;
    printf("____________________________MENU____________________________\n");

    do
    {
        printf("(F) flag a spot as a mine, (R) remove a flag, (A) assert that spot is mine free, (Q) quit the game\n");
        scanf("%c", &menu);
        getchar();
        menu = toupper(menu);
        printf("input: %c", menu);
    }while((menu != 'F') || (menu != 'R') || (menu != 'A') || (menu != 'Q'));

    printf("input successful2");

    if(menu == 'F')
    {
        printf("input successful3");
        return 0;
    }
    else if(menu = 'R')
    {
        return 0;
    }
    else if(menu = 'A')
    {
        return 0;
    }
    else if(menu = 'Q')
    {
        tearDown();
    }
    else
    {
        return 0;
    }
    return 0;
}

标签: cloopsvalidationswitch-statementdo-while

解决方案


推荐阅读