c++ if语句导致无限循环

c++ if statement is causing an infinite loop

本文关键字:无限循环 语句 if c++      更新时间:2023-10-16

在我的函数中,我添加了一个if语句来保持用户输入正确的坐标,如果第一个if语句为假,它将导致无限循环。如果第一个IF语句是正确的,第二个IF语句是假的,它就可以正常工作。

void Sheep::sheepProcess(BoardSet& board)
{
    char middle;
    cout << "Your move? ";
    cin >> x1 >> y1 >> middle >> x2 >> y2;
    if (correctInput(x1, y1, x2, y2))
    {
        convertCoordinates(x1, y1, x2, y2); //x=z and y=w
        if(board.legalMoveForSheep(z1, w1, z2, w2))
        {
            board.adjustBoardForSheep(z1, w1, z2, w2);
        }
        else
        {
            cout << "Illegal Move, Try again" << endl;
            sheepProcess(board);
        }
    }
    else
    {
        cout << "Illegal input, Try again" << endl;
        sheepProcess(board);
    }
}

如果您需要更多的代码,如bools。让我知道

编辑:

class Sheep {
public:
    void sheepProcess(BoardSet& board);
    void convertCoordinates(char x1, int y1, char x2, int y2);
    void initalizedItems();

private:
    char x1, x2;
    int y1, y2, z1, z2, w1, w2;
};

您不是在吃cin上准备好的输入。下一次读取得到的是同样的输入,同样失败,不断重复。

解决方案:当你发现现成的输入无效时,吃掉它&扔掉,向用户抱怨提供了错误的输入,并允许他重试。