Hi y'all. I'm trying to teach myself C++ for my own personal betterment. I have a little experience with JS and Java, but I'm just diving into C++.
I'm working on a tic tac toe exercise. I am running into a problem where, after I input a grid position, other parts of the array are losing their default '_' character, and sometimes it's saying a position has been taken when I know it's still open.
For example: First round, player 1 input for "1" yields:
x _ _
_ _ _
_ _ _
First round, player 2 input for "5" yields:
The spot has already been taken. Try again.
x _ _
_
_ _ _
I know it says position 5 has been taken because it no longer points to an underscore. But I'm wondering why I'm losing the underscore in the first place. I tried changing the array to a vector, but still had the same issue. If I run the code long enough, I start to get weird smiley-type characters in certain spots on the grid.
I removed some aspects of the code that I think are irrelevant to the problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
//Function setGrid initializes blank grid. Called in main.
void setGrid ( char grid [] )
{
for ( int i = 0; i < 9; i++ )
{
grid[i] = '_';
}
}
//Function showGrid displays current array, inserting line
//breaks where needed
void showGrid ( char grid [] )
{
std::cout << "\n";
for ( int i = 0; i < 9; i++ )
{
if ( i == 3 || i == 6 )
{
std::cout << "\n";
}
std::cout << grid[i] << " ";
}
std::cout << "\n";
}
//Function playSquare changes an array index to player's character
//based on input. Called in while loop in main.
void playSquare ( char grid [], char player, int input )
{
if ( input < 1 || input > 9 )
std::cout << "That number doesn't work. Try again: ";
else if ( grid[input-1] != '_' )
std::cout << "That spot's been taken. Try again.";
else
grid[input-1] = player;
}
int main() {
char p1x = 'x';
char p2o = 'o';
int userInput;
char gameGrid [9];
setGrid ( gameGrid );
showGrid ( gameGrid );
while ( !isOver || counter < 9 )
{
std::cout << "Player 1, enter your number: ";
std::cin >> userInput;
playSquare ( gameGrid, p1x, userInput );
showGrid ( gameGrid );
std::cout << "Player 2, enter your number: ";
std::cin >> userInput;
playSquare ( gameGrid, p2o, userInput );
showGrid ( gameGrid );
};
std::cout << "Game over.";
return 0;
}
|