I'm making a classic tic-tac-toe type game but with the board size defined by the user.
When trying to print the board (with asterisks representing open spaces) after the user specifies a size for the board, I'm only getting what seem to be garbage values.
#include <iostream>
#include <string>
using namespace std;
const int BOARD_MAX = 10;
const int BOARD_MIN = 3;
bool sizecheck(int);
void displayBoard(char [][BOARD_MAX], int);
int main(void)
{
int boardsize, i, j;
char grid[BOARD_MAX][BOARD_MAX];
cout << "Please enter the size of the board (" << BOARD_MIN << " - " << BOARD_MAX << "): ";
cin >> boardsize;
if ((sizecheck(boardsize)) == false)
{
do
{
cout << "Must be a number between " << BOARD_MIN << " and " << BOARD_MAX << ". Try again." << endl;
cout << "Please enter the size of the board (" << BOARD_MIN << " - " << BOARD_MAX << "): ";
cin >> boardsize;
sizecheck(boardsize);
}
while ((sizecheck(boardsize)) == false);
}
for (i = 0; i < boardsize; i++)
{
for (j = 0; i < boardsize; i++)
{
grid[i][j] = '*';
}
}
displayBoard(grid, boardsize);
return 0;
}
bool sizecheck(int fboardsize)
{
if ((fboardsize > BOARD_MAX) || (fboardsize < BOARD_MIN))
{
return false;
}
else
{
return true;
}
}
void displayBoard(char fgrid[][BOARD_MAX], int fboardsize)
{
int i, j;
for (i = 0; i < (fboardsize); i++)
{
for (j = 0; j < (fboardsize); j++)
{
cout << fgrid[i][j];
}
cout << endl;
}
}
Output:
The program is obviously a work in progress; I'm just having trouble with the printing of the array after using a function. If i try to print without the function, it works fine. I'm having a hard time figuring out what's going wrong.
Sorry for the super basic question; I'm very new to C++ and programming in general and am quite stumped.
Thanks!
check you grid init cycle...
for (i = 0; i < boardsize; i++)
{
for (j = 0; i < boardsize; i++)
There is a typo in your code where you initialize the board: It should read
for (i = 0; i < boardsize; i++)
{
for (j = 0; j < boardsize; j++)
{
grid[i][j] = '*';
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.