[英]c++ if statement is causing an infinite loop
In my function, I added a if statement to keep the users inputting the correct coordinates, if the first if statement is false, it will cause an infinite loop. 在我的函数中,我添加了一个if语句,以使用户输入正确的坐标,如果第一个if语句为false,则将导致无限循环。 IF the first if statement is correct and the second if statement is false, it works perfectly fine.
如果第一个if语句是正确的,而第二个if语句是false,则可以很好地工作。
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);
}
}
If you need more if the code, such as the bools. 如果您需要更多的代码,例如布尔值。 let me know
让我知道
Edit: 编辑:
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;
};
You're not eating the input that's standing ready on cin
. 您不会吃掉
cin
准备好的输入。 The next read is getting the very same input which also fails, repeat ad nauseam. 下一读得到的输入也完全相同,但同样失败,请重复输入广告。
Solution: When you detect there's input standing ready that's not valid, eat it & throw away, complain to user about providing bad input and allow him to retry. 解决方案:当您发现有准备就绪的输入无效时,将其吃掉并扔掉,向用户抱怨输入错误,让他重试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.