AlkamlBan alkaml
AlkamlBan alkaml

Reputation: 13

Printing a 2D char array in C++

so I have a problem with my code which I can't pinpoint. Simply put, I want to print out the contents of a 2D char array in c++ in a grid format. My code is the following (keep in mind that I dont want to change the structure of my code just find why I am not getting the desired result):

#include <iostream>
#include <string>

using namespace std;

void drawBoard(char board[3][4])
{
    int j = 0;

    for (int i = 1; i < 12; i++)
    {
        if ((i % 4) == 1 || (i % 4) == 2)
        {
            cout << " " << board[i][j] << " |";
        }
        else if ((i % 4 == 3))
        {
            cout <<  " " + board[i][j] << endl;
        }
        else
        {
            cout << "---+---+---" << endl;
            j += 1;
        }
    }
}

int main()
{
    char board[3][4] = { {' ', ' ', ' ', '\0'}, {' ', ' ', ' ', '\0'}, {' ', 
    ' ', ' ', '\0'} };
    drawBoard(board);

    cin.get();
}

What I would expect for this to give me is a basic tic-tac-toe grid with blank spaces where the X's and O's go. Instead what I get is a grid as expected with random characters placed in some of the squares and no matter how much tweaking I do gives the same or a similar result but I don't understand why. Any help would be appreciated (Also preferably not including anything beyond basic c++ like functions, loops etc since I haven't learnt those yet and we can't use them in our assignment even if we know them).

Upvotes: 0

Views: 4900

Answers (1)

Arash
Arash

Reputation: 2164

Check the array range:

char board[3][4]

Then you have:

board[i][j]  ->  board[1,2,3,5,6,7,9,10,11][j] 

No matter what i%4 is, what is put in board is i not i%3.

Use either structures:

for i
   for j
      board[i][j]

or

for i
   ((char*)board)[i]

I have edited your code:

#include <iostream>
#include <string>

using namespace std;

void drawBoard(char board[3][4])
{
    for (int i = 0; i < 12; i++)
    {
        if(i%4!=3)
        {
            cout<<" "<<board[i/4][i%4]; // board[0 to 2][0 to 2, 3 skept]
            if(i%4<2)
                cout<<" |";
        }
        else
        {
            if(i/4<2)
                cout<<endl<< "---+---+---";
            cout<<endl; // new line
        }
    }
}

int main()
{
    char board[3][4] = { {'x', 'o', 'x', '\0'}, {'o', 'x', 'x', '\0'}, {'o', 
    'o', 'x', '\0'} };
    drawBoard(board);

    cin.get();
}

Results:

 x | o | x
---+---+---
 o | x | x
---+---+---
 o | o | x

Upvotes: 1

Related Questions