0

I'm making a card dealing game. I'm having trouble parsing a string into components in order for me to keep track of the suits and values being drawn.

const string rank[] = { "Ace", "2", "3", "4", "5", "6", "7",
                    "8", "9", "10", "Jack", "Queen", "King" };
const string suit[] = { "Clubs", "Diamonds", "Hearts", "Spades" };

string random_card(bool verbose=false) {
  string card;
  card = rank[ rand()%13 ];
  card += " of ";
  card += suit[ rand()%4 ];
  if (verbose)
    cout << card << "\n";
  return card;
}

How do I break card down into components to keep track of the suits and values in a table?

Edit: I must use a string for this assignment. I cannot change the way that the card is generated. I must parse the string into components and keep track of the values for each suit in a table, which I then need to format and print into stdout.

2 Answers2

0

Don't use a string to represent a card, just define a simple struct

struct Card
{
    int suit;
    int rank;
};
john
  • 85,011
  • 4
  • 57
  • 81
  • I forgot to mention, I am limited to using this method as it is part of an assignment. My task is to figure out how to parse the card string into components and keep track of the values for each suit in a table. Thank you for the quick response! – Jake Hafendorfer Sep 14 '13 at 21:30
  • Add the requirement to the question. – EvilTeach Sep 14 '13 at 21:32
  • Well I guess you have to split the card string at the spaces and look up the substrings in your arrays of ranks and suits. Ugly. – john Sep 14 '13 at 21:32
0

Try something like this:

string delimiter = " of ";
int delimiter_length = delimiter.size();

string card = "Ace of Clubs";
int del_begin = card.find_first_of(delimiter);
int del_end = del_begin + delimiter_length; 

string rank = card.substr(0, del_begin); 
string suit = card.substr(del_end, card.size() - del_end);
Hlib Babii
  • 599
  • 1
  • 7
  • 24