Search code examples
c++arraysloopsvariablesstructure

Create sequential variable names using a loop in C++


I'm trying to create variable names using a loop.

Specifically, I am using this structure:

struct card{
    string rank;
    string suit;
};

This is the rest of my code as it stands, and where it says "card+i" is where I need it to say "card1", or "card2", etc.

string aSuit[4] = {" Hearts"," Clubs"," Diamonds"," Spades"};
string aRank[13] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
string aDeck[52];

int main(int argc, char *argv[])
{
    int i = 0;
    for (int s=0; s<4; s++) {
        for (int r=0; r<13; r++) {
            card card+i;
            card+i.rank = aRank[r];
            card+i.suit = aSuit[s];
            cout << card + i.rank << card + i.suit << endl;
            i++;
        }
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

Solution

  • Use arrays instead:

    card cards[52];
    
    int main(int argc, char *argv[])
    {
        int i = 0;
        for (int s = 0; s<4; s++) {
            for (int r = 0; r<13; r++) {
                cards[i].rank = aRank[r];
                cards[i].suit = aSuit[s];
                cout << cards[i].rank << cards[i].suit << endl;
                i++;
            }
        }
        system("PAUSE");
        return EXIT_SUCCESS;
    }