在我的函数中,我添加了一个if语句来保持用户输入正确的坐标,如果第一个if语句为false,则会导致无限循环。如果第一条if语句是正确的,第二条if语句是错误的,那么它工作得很好。C++ 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;
};
只有当您继续提供无效输入。尽管如此,这比循环更适合循环。 – 2013-04-07 20:23:22
您是否将字符输入到数字中? – chris 2013-04-07 20:24:06
如果不纠正,只需要给一次无效输入,以便将来调用'cin >> ...'失败。 – 2013-04-07 20:24:07