Hello everyone, I just started programming a few months ago and now I have decided to start a Tic-Tac-Toe program in C++ to test my skills of arrays and more. So far, everything has been working fine and the program has been compiling, however, there is one problem. Every time I enter 3,3 for the rows and columns, the program fills in the spaces 3,3 AND 2,3. When I input 2,3, the program does not fill any spaces at all. Could someone help me find out how to fix this issue? Thanks.
// Tic-Tac-Toe
#include "stdafx.h"
#include <iostream>
usingnamespace std;
char board [3] [3]= { { '-','-','-'} , {'-','-','-'} , {'-','-','-'} };
void DisplayBoard()
{
//displays the recent playing board
cout << " 1 2 3" << endl;
cout << "1 " << board [0][0] << " " << board [0][1] << " " << board [0][2] << endl;
cout << "2 " << board [1][0] << " " << board [1][1] << " " << board [2][2] << endl;
cout << "3 " << board [2][0] << " " << board [2][1] << " " << board [2][2] << endl;
}
int main(int nNumberofArgs, char* pszArgs[])
{
DisplayBoard();
int row;
int column;
bool i;
int row2;
int column2;
//---------------------------------------
//--------------- Turns -----------------
//---------------------------------------
while (i == false)
{
//player 1s move
cout << "Player one, enter your choice (row and column)";
while(row >= 1 || row < 4)
{
cin >> row;
if ((row>=4) || (row<1))
cout<<endl<<"Invalid move. Try again with numbers from 1 to 3: ";
elsebreak;
}
while(column >= 1 || column < 4)
{
cin >> column;
if ((column>=4) || (column<1))
cout<<endl<<"Invalid move. Try again with numbers from 1 to 3: ";
elsebreak;
}
row--;
column--;
board [row] [column] = 'X';
DisplayBoard();
//player 2s move
cout << "Player two, enter your choice (row and column)";
while(row2 >= 1 || row2 < 4)
{
cin >> row2;
if ((row2>=4) || (row2<1))
cout<<endl<<"Invalid move. Try again with numbers from 1 to 3: ";
elsebreak;
}
while(column2 >= 1 || column2 < 4)
{
cin >> column2;
if ((column2>=4) || (column2<1))
cout<<endl<<"Invalid move. Try again with numbers from 1 to 3: ";
elsebreak;
}
row2--;
column2--;
board [row2] [column2] = 'O';
DisplayBoard();
//---------------------------------------
//---------------------------------------
//---------------------------------------
}
system("PAUSE");
return 0;
}
The result for row: 3 column: 3:
1 2 3
1 - - -
2 - - -
3 - - -
Player one, enter your choice (row and column)3
3
1 2 3
1 - - -
2 - - X
3 - - X
Player two, enter your choice (row and column)
The result for row: 2 column: 3 :
1 2 3
1 - - -
2 - - -
3 - - -
Player one, enter your choice (row and column)2
3
1 2 3
1 - - -
2 - - -
3 - - -
Player two, enter your choice (row and column)
On line 16, you print out board[2][2] instead of board[1][2].
You should also initialize your variables starting at line 25 to default values. Uninitialized variables get garbage values and could be anything at runtime. For example, line 35 is basically random - i could be either true or false.