1

在我的函数中,我添加了一个 if 语句来保持用户输入正确的坐标,如果第一个 if 语句为 false,则会导致无限循环。如果第一个 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;
};
4

1 回答 1

0

你没有吃掉准备好的输入cin。下一次读取得到相同的输入,但也失败了,重复令人作呕。

解决方案:当您检测到有无效的输入准备就绪时,吃掉它并扔掉,向用户抱怨提供了错误的输入并允许他重试。

于 2013-04-09T06:23:28.467 回答