Hi, I am working on a lab assignment and I am having trouble with this one section. I need to write something that will print an error message and not run the program if the user enters anything besides lowercase x's and o's. This is what I have so far
1 2 3 4 5 6 7 8 9 10 11
// Check board contains only x's and o's
bool valid = true;
//TBA
if (!valid)
{
cout << "Sorry, you can only enter x's and o's\n";
exit(1);
}
suggests that you have some sort of array or structure where the board data is stored, and that you want to check the entire board?
Or do you really just want to check the last character entered by the user?
As a matter of user-friendly design, it might be a good idea to allow the user to enter either upper or lower case characters, and convert the input to lower case just after it has been input, before the validation.
#include <cstdlib>
#include <iostream>
usingnamespace std;
int main()
{
// Declare 2D array
constint SIZE = 3;
char board[SIZE][SIZE];
// Read x's and o's
cout << "Enter x's and o's on board (L-R, T-B): ";
for (int r = 0; r < SIZE; r++)
for (int c = 0; c < SIZE; c++)
cin >> board[r][c];
// Print 2D array
cout << "\n+---+---+---+\n";
for (int r = 0; r < SIZE; r++)
{
cout << "| ";
for (int c = 0; c < SIZE; c++)
cout << board[r][c] << " | ";
cout << "\n+---+---+---+\n";
}
// Check board contains only x's and o's
bool valid = true;
if (!valid)
{
cout << "Sorry, you can only enter x's and o's\n";
exit(1);
}
// Check first diagonal to see who wins
char winner = ' ';
if ((board[0][0] == board[1][1]) &&
(board[1][1] == board[2][2]))
winner = board[0][0];
// Check second diagonal to see who wins
if ((board[0][2] == board[1][1]) &&
(board[1][1] == board[2][0]))
winner = board[0][0];
// Check rows to see who wins
for (int r = 0; r < SIZE; r++)
if ((board[r][0] == board[r][1]) &&
(board[r][1] == board[r][2]))
winner = board[r][0];
// Check columns to see who wins
for (int c = 0; c < SIZE; c++)
if ((board[c][0] == board[c][1]) &&
(board[c][1] == board[c][2]))
winner = board[c][0];
// Print winner
if (winner != ' ')
cout << "Congratulations " << winner << " is the winner\n";
else
cout << "Sorry, no one wins\n";
return 0 ;
}
I also need to fix the column section of the code but it's not my priority right now. On normal circumstances I would use the upper to lower idea but because this is just a lab and I'm not concerned with it being perfect.
That if statement is quite tricky because it is checking for two possible values, and a common mistake is to put a logical or || in the middle. But because you are checking for not-equal, the logical and && is needed.
Another way to write it is like this, with an extra set of parentheses:
Chervil - this was a great point, I was doing exactly(!) the same and v nicely put
That if statement is quite tricky because it is checking for two possible values, and a common mistake is to put a logical or || in the middle. But because you are checking for not-equal, the logical and && is needed.