DavidJ85 DavidJ85 - 1 year ago 103
C++ Question

How do you assign two types of data to one variable?

I just started to learn C++ a couple weeks ago and I am trying to make a Blackjack game now.
What I attempted to do was create an array that contained variables of all the cards such as: h1, hj, c4, ck; These stand for hearts 1, hearts jack, clubs 4, and clubs king.

I would like these variables to contain both a string (The name of the card) and an integer (the value of the number for adding).

Is there a way to have a variable contain two values?


Answer Source

Simply speaking there's two solutions:

1) Use a tuple

std::tuple<std::string,int> Hearts1=std::make_tuple("h1", 12);
std::tuple<std::string,int> Clubs1=std::make_tuple("c1", 13)

See more: http://en.cppreference.com/w/cpp/utility/tuple

2) Use Objects

class Hearts
  std::string name;
  int value;

class Clubs
  std::string name;
  int value

int main()
  Clubs CO; CO.name="abc"; CO.value=12;
  Hearts HO; HO.name="dce"; HO.value=13;

I suggest learning the basics of C++ programming prior to undertaking such a project. I strongly recommend "The C++ Programming Language"(B.Stroustrup) to get started with.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download