Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 297
  • Last Modified:

Logic on my program

The purpose is to randomly print out five cards...
What I have compiles but does not work:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>

using namespace std;

int main()
   char rank[] = {'2','3','4','5','6','7','8','9','T','J','Q','K','A'};
   char suit[] = {'C','D','H','S'};

   const int SUITS = 4;
   const int RANKS = 13;
   const int N = SUITS * RANKS;
   const int NUMCARDS = 5;

   char deck[N];
   bool used[N];

   for (int i = 0; i < N; i++)
         used[i] = false;

   for (int i = 0; i < RANKS; i++)
           for (int j = 0; j < SUITS; j++)
                     deck[SUITS * i + j] = rank[i] + suit[j];

   for (int i = 0; i < N; i++)
           int r = i + (rand() * (N - i));
             //int r = i + rand() / (RAND_MAX / (N - i) + 1);
             char t = deck[r];
             deck[r] = deck[i];
             deck[i] = t;

   for (int i = 0; i < NUMCARDS; i++)
         cout << deck[i] << endl;

   return 0;

My problem I believe lies on this line
deck[SUITS * i + j] = rank[i] + suit[j];

How can I fix my code here?

Also-This line
//int r = i + rand() / (RAND_MAX / (N - i) + 1);
I found online from stanford..does it look fair

I want to check for cards that have been used thus
 bool used[N];

   for (int i = 0; i < N; i++)
         used[i] = false;
Where would be the best place to place it...
1 Solution
Kent OlsenData Warehouse Architect / DBACommented:
Hi CPlusJavaCSharp,

You're correct in that the problem lies with this line:

  deck[SUITS * i + j] = rank[i] + suit[j];

The underlying type for both rank[] and suit[] is char, which is an 8-bit integer.  C++ is dutifully adding the characters together when what you seem to want is to concatenate them.

The easiest solution might be a simple function that Deck() that puts the two characters together into a string.

char *Deck (int Suit, int Rank)
  static Name[4];

  Name[0] = suit[Suit];
  Name[1] = ' ';
  Name[2] = rank[Rank];
  Name[3] = 0;
  return Name;

Note that you'll need to move the declarations for rank[] and suit[] to global storage.  But that's something that you should do anyway.  It usually not a good idea to initialize arrays on the stack.

Good Luck,

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now