While loop在碰到break后再进行一个循环

While loop makes one more loop after it hits break

本文关键字:循环 一个 loop break While      更新时间:2023-10-16

我得到了用方法制作的小井字。然而,它并没有像预期的那样工作。在有了3行之后,它不会立即退出循环,而是再执行一次,然后结束它

while(1){                  // infinite loop until someone has won, or the board is full
   game.printBoard();         //prints the board
   game.move();               // player enters a move
   if(game.checkWin())        //returns 1 if there are 3 in row by same mark or 0 if
   //                          the condition is not met 
   {
        break;
   }
}   // end of while loop

在第3行之后,它转到函数"game.checkWin()",并返回1,执行break语句并结束while循环。

checkWin()中的一些代码:

bool TicTacToe::checkWin()    //this function belongs to a calss
{
     //checks for 3 in row 1-2-3 by the same mark, this is made for all combinations
    if(_board[0] == _turn && _board[1] == _turn && _board[2] == _turn)
    {
        cout << _turn << " has won the match by: 1-2-3n";
        return 1;       // returns 1 meaning that somebody has won
    }
   ......   //same code as above but with different positions
    return 0    // returns 0 meaning that nobody has met the winning conditions
}     // ends of the function

编辑:代码的其余部分

class TicTacToe
{
public:
    void setBoard(); //sets the board
    void printBoard(); //prints the board
    void move();   // user makes a move
    bool checkInput(); // checking whether the move is valid
    bool checkWin(); //chekcs for win
private:
    char _turn = 'X'; // players turn
    char _board[9]; // the board
    int _position; // the int used for cin
};
void TicTacToe::move()   // user is about to enter a move
{
    if(checkInput())    // let user enter a valid move
    {
        _board[_position - 1] = _turn;  // setting the board to it's mark
        (_turn == 'X')? _turn = 'O': _turn = 'X'; // switching from X to O and vice versa
    }
}
bool TicTacToe::checkInput()   // function called only with the TicTacToe::move() function
{
    cout << "It is " << _turn << " turn!n";
    cout << "Please enter one of the available squares!n";
    cin >> _position;
    if (!(_position >= 1 && _position <= 9))
    {
        cout << "Error! Invalid input!n";
        return 0;   //meaning the user is not allowed to enter that position
    }
    else if(_board[_position - 1] != '_')
    {
        cout << "Error! There is already a mark!nPlease enter another square!n";
        return 0;  //meaning the user is not allowed to enter that position
    }
    return 1; //means that position is valid and proceeds to change the board
} // end of the function
int main()
{
    cout << "Welcome to TicTacToe!n";
    TicTacToe game;
    game.setBoard();
    while(1){
    .......          // some code already shown above
    }              // end of while loop
    cout << "Thank you for playing!n";
    return 0;
}

因为在移动中,你需要移动,更换玩家,然后检查(现在的另一个)玩家是否有。