skipper skipper - 2 months ago 10
C++ Question

c++ Multidimensional array wont initialize

I have been trying to get this to work correctly; however it seems I can not figure this out. I am trying to get a game board to initialize correctly but it keeps saying that

<error reading characters of string>
.

using namespace std;

int main()
{

board show;
show.init();
show.printing();

}


class board {

public:
void init(){

string Board[8][9] = {
{ "C56", "C15", "C21", "C62", "C11", "C62", "C21", "C15", "C56" },
{ " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
{ " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
{ " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
{ " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
{ " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
{ " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
{ "C56", "C15", "C21", "C62", "C11", "C62", "C21", "C15", "C56" },
};
}

void printing(){

string character = "*";

int position[2] = { 2, 2 };
// Draw the grid once
for (int i = 0; i < 8; i++){
for (int j = 0; j < 9; j++){
if (i == position[0] && j == position[1])
cout << character;
else
cout << Board[8][9];
cout << " ";
}
cout << endl;
}
}

private:
string Board[8][9];
};

Answer

it's so easy: you have the half solution: just use for loop to copy values

void A::init()
{
    string Board[8][9] = {
        { "C56", "C15", "C21", "C62", "C11", "C62", "C21", "C15", "C56" },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { "C56", "C15", "C21", "C62", "C11", "C62", "C21", "C15", "C56" },
    };

    for(int i(0); i < 8; i++)
    {
        for(int j(0); j < 9; j++)
            this->Board[i][j] = Board[i][j];        
    }
}