gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:08:34 25 4
gpt4 key购买 nike

在我的函数中,我添加了一个 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);
}

}

如果你需要更多的if代码,比如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 上准备好的输入。下一次读取得到的是同样的输入,但同样失败了,令人作呕的重复。

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

关于c++ if语句导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15867377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com