There are a number of problems with the code, most notably that you have off-by-one index accesses. Array indices start at 0,
not at 1.
Second, you should have a look at for loops, which are used whenever you need a loop with a counter.
Next, you have temp and cardPulled as global variables, but that isn't right. The card that is drawn from the deck should be returned by the function - not stored in some global variable. temp is used inside the pullRandomCard(), therefore it should be declared there. Something like randVal would be a better name anyway.
As for setting a card to NULL... you should note that NULL is just a macro define for 0. NULL should only be used to indicate that you mean a null pointer. Since you have no pointers here, that is not applicable.
Instead of doing that, you should actually
remove the card from the array, which requires you to keep track of the current number of cards in the deck. At least in theory, because in practice you should use std::vector, which works like a dynamic array - you can add and remove elements at random without having to know the max number of elements in advance.
Last, don't include the srand call in pullRandomCard - whenever you initialize the pseudo-random number generator with the same value (which happens here when you call the function more than once per second), it will generate the same sequence of random numbers. Move the srand call to the beginning of main() - it should be called just once.
Oh, and a better name for sortedDeck would be either sortDeck - but since it doesn't really sort the deck, perhaps it should be called setupDeck or similar. It is also common practice to let variable and functions name start with a lowercase letter (i.e. deck instead of Deck).
So in my eyes, a proper implementation would be the following (with the exception that there should be an additional class "Deck" that manages the cards):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include <vector>
using namespace std;
struct Card
{
int value;
char suit;
Card() {}
Card(int value,char suit) : value(value), suit(suit) {}
};
vector<Card> deck;
void setupDeck()
{
deck.clear();
static const char[]={'c','d','h','s'};
for (int suit=0;suit<4;suit++)for (int val=1;val<=13;val++)deck.push_back(Card(val,suit));
}
Card drawRandomCard()
{ //you should probably handle the case when the deck is empty
int randIndex=rand()%deck.size();
Card drawnCard=deck[randIndex];
deck.erase(deck.begin()+randIndex);
return drawnCard;
}
|