在我的函數中,我添加了一個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