Search code examples
arraysnumbers2dcharacterinitializing

Initializing a number and a char to a 2D array


I have to implement a deck of cards with a number and a letter. This is what I have done so far:

string deck [6][6] =
{
    {1A, 1B, 1C, 1D},
    {2A, 2B, 2C, 2D},
    {3A, 3B, 3C, 3D},
    {4A, 4B, 4C, 4D},
    {  ,   ,   ,   };

};
int main ()
{
   cout << deck[0][0] << endl;
}

I get an error:

invalid suffix 'A' on integer constant


Solution

  • You are getting this error because you need to wrap your strings in double quotations. If you want to use a static initialization/declaration, it should look something like this:

    std::string deck[4][4] = {
        { "1A", "1B", "1C", "1D"}, 
        { "2A", "2B", "2C", "2D"}, 
        { "3A", "3B", "3C", "3D"}, 
        { "4A", "4B", "4C", "4D"}
    };
    

    You can display the entire contents of the deck by using two nested for loops:

    for (int r=0; r < 4; ++r) {
        for (int c=0; c < 4; ++c) {
            if (c > 0) {
                cout << " ";
            }
            cout << deck[r][c];
        }
        cout << "\n";
    }