0

I have been learning C++ for a few weeks and I am now trying to program a little thing by myself and practice what I learned at the same time.

So my program is a poker hand distributor.

I started by creating a simple "card" class which contains two methods, value and suit.

At first I tried to do an enum for both, but I couldn't set the enum with integers (for exampleenum value {2,3,4,5,6,7,8,9,T,J,Q,K,A} doesn't work, which is normal.

My enum for suits works just fine, it's just that when I want to print a card (i implemented operator<< in my class) I don't know how to convert my integers to the corresponding suits. I will get for example 10 1 for ten of spades. I would like to know how to convert this in my operator<<() function to get something like T s when I want to print a card using cout << card which contains the informations 10 and 1

;

;

tldr I want to know how to convert for example "10 1" to "T s (T spades)" while keeping 2 to 9 as such (9 1->9 s)

Thank you!!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

1 Answers1

3

I want to know how to convert for example "10 1" to "T s (T spades)" while keeping 2 to 9 as such (9 1->9 s)

You can use couple of arrays to map the numbers to strings.

std::string valueMap[13] = {"A", "2", ..., "Q", "K"};
std::string suitMap[4] = {"Clubs", "Diamonds", "Hearts", "Spades"};

Assuming you use an enum with values 1-13 for the value and an enum with values 1-4 for the suit, you can use valueMap[value-1] to get the string for the value and use suitMap[suit-1] to get the string for the suit.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    This solution is indeed better. If you use an enum, you can't directly use the names you put in your enum. Only the compiler knows them, they are implicitly associated to numbers in the final program. Using an enum you would have to create a function implementing a `switch(...) { ... }` to return the corresponding value. With the solution above you can just use directly the string. – Benjamin Barrois Jul 25 '18 at 15:18
  • @BenjaminBarrois This is compatible with enums. – eesiraed Jul 25 '18 at 17:04
  • Thank you very much, this is what I used, plus an int to string function that convert the int to valueMap[int-1]. I did not think to use the numbers as strings. I guess it will come with time! Thank you again. – Tommy-Xavier Robillard Jul 25 '18 at 17:54
  • @Tommy-XavierRobillard, you are welcome. Glad I was able to help. Yes, you will learn the tricks of the trade as time goes by :) – R Sahu Jul 25 '18 at 17:58
  • @FeiXiang Yes it is compatible with enum, but if you want to output a string having the same name as your enum entries, you have to associate them by hand, you can't use the name as it is. – Benjamin Barrois Jul 26 '18 at 14:33