vendredi 21 octobre 2016

Code overwrites variables although it should not

the following code snippet is a part of a TicTacToe game. The problem I have is, that whenever I run the code and get to the point where I enter the row and column the code works just fine except for one thing. When I enter row 1 column 1 the code will display the first X properly but the moment I enter a second row 1 column 1 it switches the X in the grid with an O although it should not. I thought the condition in the do while loop was enough to not let the grid be overwritten when entering a row/column combination a second time. But it seems it does not.

char grid[3][3] = { 
    {' ', ' ', ' '},
    {' ', ' ', ' '},
    {' ', ' ', ' '}
    };

do {
    int row, column;
    for (int i = 1; i <= 9; i++)
        do {
            ...
            ...
            std::cout << "* Enter row   : ";
            std::cin >> row;
            std::cout << "* Enter column: ";
            std::cin >> column;

        } while ((row < 1 || row > 3) && (column < 1 || column > 3) && (grid[row-1][column-1] != ' '));

        if (i % 2 == 0)
            grid[row-1][column-1] = 'O';
        else
            grid[row-1][column-1] = 'X';
    }   // For loop close
} while (true);

Hope you guys can help me out there. Have a nice evening. Cheers.

Aucun commentaire:

Enregistrer un commentaire