无限循环 - char关闭不工作的C ++

时间:2014-01-12 03:13:19

标签: c++

该行:

cin >> cRestart;

正在捕获char,但while循环没有终止。我需要代码继续前进。你能帮帮忙吗? (while循环查找y,Y,n和N,以防您无法看到所有内容。)

    bool startInputValidation()
    {
        char cRestart = 'b';            //set initial value at b to run while loop

        conRGB(COLOUR_WHITE);           //text colour white

        conXY(0, 19);                   //cursor position in console
        drawLine();                     //draws a horizontal line across screen
        conXY(0, 23);
        drawLine();

        while (cRestart != 'y' || cRestart != 'Y' || cRestart != 'n' || cRestart != 'N')    //check for correct input (Y/N)
        {
            conXY(21, 21);
            for(int iCount = 0; iCount < 139; iCount++)                                     //blank lines
            {
               cout << " ";
            }
            conXY(21, 21);
            cout << "ARE YOU SURE YOU WISH TO CONTINUE Y/N?   ";                                    //ask question
            cin >> cRestart;                                                                //get input from user
        }

        if (cRestart == 'y' || cRestart == 'Y')                                             //if yes return true
        {
            return true;
        }
        else
        {
            return false;
        }
    }

2 个答案:

答案 0 :(得分:3)

叹息,另一位忘记了摩根法律的程序员。它应该是:

    while (cRestart != 'y' && cRestart != 'Y' && cRestart != 'n' && cRestart != 'N')    //check for correct input (Y/N)

答案 1 :(得分:0)

此控制结构

    char cRestart = 'b';            //set initial value at b to run while loop
    // ...

    while (cRestart != 'y' || cRestart != 'Y' || cRestart != 'n' || cRestart != 'N')    //check for correct input (Y/N)
    {
        conXY(21, 21);
        for(int iCount = 0; iCount < 139; iCount++)                                     //blank lines
        {
           cout << " ";
        }
        conXY(21, 21);
        cout << "ARE YOU SURE YOU WISH TO CONTINUE Y/N?   ";                                    //ask question
        cin >> cRestart;                                                                //get input from user
    }

1)无效(在while循环中条件无效 2)看起来很糟糕(最好使用另一种控制结构)

我会按照以下方式编写函数

bool startInputValidation()
{
    char cRestart;                  //set initial value at b to run while loop

    conRGB(COLOUR_WHITE);           //text colour white

    conXY(0, 19);                   //cursor position in console
    drawLine();                     //draws a horizontal line across screen
    conXY(0, 23);
    drawLine();


    do
    {
        conXY(21, 21);
        for ( int iCount = 0; iCount < 139; iCount++ )
        {
           cout << ' ';
        }

        conXY(21, 21);
        cout << "ARE YOU SURE YOU WISH TO CONTINUE Y/N?   ";

        cin >> cRestart;
        cRestart = toupper( cRestart );
    } while ( cRestart != 'N' && cRestart != 'Y' )

    return cRestart == 'Y';
}