Here is my new edited code I am having trouble with my final if loop for the X and O’s stored inside an array. I am trying to check if there is an X or O already inside the array or not. If there is one it asks the user for another input then start over again however when i run the program this happens:
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
Please Enter Box Number: 1
player X your number is 1
X | 2 | 3
4 | 5 | 6
7 | 8 | 9
Please Enter Box Number: 1
Please enter another Number2
player O your number is 1
O | 2 | 3
4 | 5 | 6
7 | 8 | 9
Please Enter Box Number:
char c;
cout << "Please Enter Box Number: ";
cin >> c;
if (c > '9' || c < '0')
{
// error message
cout << "please enter a number 1-9" << " ";
cin >> c;
cin.ignore(numeric_limits<int>::max(), '\n');
}
if (c < '9' || c > '0')
{
int number = c - '0';
if (board[number - 1] == 'X' || board[number - 1] == 'O')
{
cout << "Please enter another Number";
cin >> c;
cin.ignore(numeric_limits<int>::max(), '\n');
}
else if (board[number -1] != 'X' || board[number - 1] != 'O' ) {
if (player == 'X')
{
player = 'O';
}
else
{
player = 'X';
}
cout << "player " << player << " your number is " << number << endl;
// Your implementation here...
board[number - 1] = player;
}
}
}
First the second question (the easy one):
Return exits from the current function. So, after the return, no further instruction in your function is executed. You should remove the return and put the rest of the code (that should not be executed if the input is not valid) in the else block of that if.
First question:
Why do you check that the index of each position in the array (as in board[7] = ‘8’). You already know the position, what you need to mark in each cell is the player who uses it; for example set values of ‘X’ (player 1), ‘O’ (player 2), ‘ ‘ (empty).
Instead of nine “if”, it will be easier if you convert your input ‘c’ into an integer and use it as an index. With ASCII characters (I do not know if this still workds with WCHAR, UTF-8 and so on) you could make it quick and dirt:
int k = c - '0';board[k] = player;Edit:
Taking into account checking that the square is not already used: