Create sequential variable names using a loop in C++

29,065

Solution 1

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;
}

Solution 2

You think this is the best solution, but I can assure you, it is not. Tying your logic to the names of variables is a bad, bad idea, from a logical as well as maintenance standpoibnt. What you really want is a collection which can associate one piece of data (in this case, a string) with another.

Look into a data structure like a map

Share:
29,065

Related videos on Youtube

chuckieDub
Author by

chuckieDub

Updated on June 06, 2020

Comments

  • chuckieDub
    chuckieDub almost 4 years

    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;
    }
    
    • BoBTFish
      BoBTFish over 11 years
      This isn't possible, variable names all disappear at compile time. Maybe use a std::map? (Ok strictly that's not entirely true, what with debug symbols, dynamic linking, etc).
    • matt
      matt over 11 years
      But isn't this exactly why there are arrays?
  • chuckieDub
    chuckieDub over 11 years
    The issue I'm having using an array, is to preserve the .suit and .rank of each card in the array. Would I need to create an array[104] {card1.rank, card1.suit, card2.rank, card2.suit, etc...} ?
  • Joseph Mansfield
    Joseph Mansfield over 11 years
    @user1846123 You've got an array of the wrong things. You don't want an array of string. See my answer.
  • paxdiablo
    paxdiablo over 11 years
    @user1846123, the answer to that is to define an array of that structure of yours, and use things like card[7].rank.