Hi,

I want to fill an array with enum Values but using integers in a loop. My set method accepts Enum types and not integers. But when I work with the enums I can use 0,1,2,3 etc.

I am trying to fill a deck of cards using some loops. Is there an easier way to do this than writing loads of code?

enum Suit {Hearts, Clubs, Diamonds, Spades};
enum Value {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace};

//set method for the type that cards is has the signature:
void set(Value v, Suit s);

void Deck::reset(void) {
        int dnumber = 0;


        for(int j=0; j<4; j++) {//suit
            for (int i=0; i<13; i++) { //value
            cards[dnumber].set(i,j); //the compiler doesn't like this line - 
            dnumber++;
            }
        }
    }

I get this:

error: invalid conversion from `int' to `namespace::Value'
error: invalid conversion from `int' to `namespace::Suit'

Recommended Answers

All 3 Replies

enum Suit {Hearts, Clubs, Diamonds, Spades};
enum Value {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace};

//set method for the type that cards is has the signature:
void set(Value v, Suit s);

void Deck::reset(void) {
		int dnumber = 0;
		
		
		for(int j=0; j<4; j++) {//suit
			for (int i=0; i<13; i++) { //value
			cards[dnumber].set(i,j); //the compiler doesn't like this line - 
			dnumber++;
			}
		}
	}

I had a similar example in a book I just read (Beginning C++ Through Game Design). Perhaps try the same technique.
First initialize i and j using values from your enums. Then when calling set() cast the values from int to either Value or Suit as necessary.

From my book's example:

for (int s = Card::CLUBS; s <= Card::SPADES; ++s) {
  for(int r = Card::ACE; r <= Card::KING; ++r) {
    Add(new Card(static_cast<Card::rank>(r), static_cast<Card::suit>(s)));
  }	//end rank for
}	//end suit for

[offTopic]
About the book:
It's not a bad book, it's good for getting going quickly because it covers alot of the basics and just scratches the surface of some of the more complex concepts. I don't think I would consider it a must-have though. It really just glosses over everything it covers and doesn't get very detailed. It has just enough information on each topic to get you going, but you'll need to supplement it with something much more thorough to really learn it well. I won't recommend against it, because you can always learn something new, but I did find most of it to be a little below my current level.[/offTopic]

cool, thanks very much Ill give it a go. I am using Ira Pohl's C++ for C programmers. But I will check out the library for this book you have mentioned.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.