are global variables try to avoid them as any line of code can change them and it is harder to track down where it went wrong. It is usually better to define them in "main" and pass them to the functions that need them.
Your if statement if (grid[i][j] == choice) is comparing an "int" to a "char". The number 1 and the char '1' have two different values (1) and (49). These would never be considered equal. You could define "choice" as a "char" and then you would be comparing the same type of variables.
I will work up a little program to give it a better test.
PS n isn't used so far. If it is the number of spaces available for a move then the game is over when n == 0, or when someone has won. So that wouldbe part of the while condition.
Note also that there is still lots of work to define a win or drawer and then how the computer makes a move.
Also have to alternate between player and computer in the loop.
Hi all, thanks for your input, Handy Andy, i changed the int to a char and now it works fine. There is a lot more to it which i didn't post as this was the only problematic function.
n merely tracks the amount of turns that have gone and won't allow it to surpass 9 for obvious reasons. I also have a draw scenario that works fine.
Again, i appreciate the help, it's been doing my head in
#include <cctype>
#include <iostream>
#include <iomanip>
#include <limits>
constexprint MAXROW{ 3 }, MAXCOL{ 3 };void draw(char grid[][MAXCOL])
{
std::cout << std::endl;
for (int i = 0; i < 3; i++)
{
std::cout << " ";
for (int j = 0; j < 3; j++)
{
std::cout << grid[i][j] << " ";
}
std::cout << std::endl;
}
}
void input(char grid[][MAXCOL], char player)
{
char choice;
//std::cout << std::endl;
std::cout << "\n Please select where you want to go: ";
std::cin >> choice;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (grid[i][j] == choice)
grid[i][j] = player;
elseif((grid[i][j] == 'X' || grid[i][j] == 'O'))
std::cout << "\n Square already taken!\n";
}
//std::cout << std::endl;
}
}
int main()
{
bool cont{ true };
char yesNo{};
char grid[MAXROW][MAXCOL] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };constexprchar player = 'X';
constexprchar computer = 'O';
int n;
do
{
draw(grid);
input(grid, player);
draw(grid);
std::cout << "\n Do another? ";
std::cin >> yesNo;
if (std::toupper(yesNo) != 'Y') cont = false;
} while (cont);
// A fair C++ replacement for "system("pause")". Or a way to pause the program.
// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue: ";
std::cin.get();
return 0; // <--- Not required, but makes a good break point.
}
The do/while loop in "main" is just for testing for now, but you may find it useful in the future.