Вопрос

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.

Это было полезно?

Решение

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

Другие советы

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

struct Card
{
    int suit;
    int rank;
};
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top