I am completely new to C++. I have a function that deals cards for a blackjack game. To do this, I need to call this function 10 times (two cards each for 4 players and a dealer). But it just deals the same card to everyone. I think it might be because I seeded srand() with time(), and then call the function many times within the same second, but that's how I need it to operate. Here's a stripped down version of my code:

void deal_card(int &suit, int &value) {
     int num_cards = 3;
     int randIndex;
     randIndex = rand() % num_cards;
     int deck[][2] = {{1, 2}, {1, 3}, {1, 4}};
     suit = deck[randIndex][0];
     value = deck[randIndex][1];
int main() {
     int bs, bv, as, av, cs, cv;
     deal_card(bs, bv);
     cout << bs << " " << bv << endl;
     deal_card(as, av);
     cout << as << " " << av << endl;
     deal_card(cs, cv);
     cout << cs << " " << cv << endl;
     return 0;

Of course with #include <iostream> and <cstdlib>.
Can someone help me deal 3 RANDOM cards? As a side issue, I'm not sure how to remove a card from deck[] after it's been dealt to ensure no two player get the exact same card. I'm sure my code is sloppy, but this is a project to help me learn. Thanks.

Recommended Answers

All 6 Replies

Unless you are using millions (maybe even billions) of random numbers in your program, you only ever need to call srand() once in your entire program. Make it the first command of your main() and remove it from deal_card(), then leave the rest of your program as-is.

I moved srand() to the first line in main. Still the same problem though. I get a different card each time I execute the program, but that card is dealt to every player. I tried to use timeofday() (as seen on Google), but the compiler doesn't recognize that. Any other suggestions?

Never mind. I found where I had srand() twice! I guess while I was messing around with it and moving it around, I accidently created it twice. There is now no calls to srand() in my function and it works as it should. thanks. Any suggestion for removing dealt cards from deck[]? or is this a topic for a new thread?

If you go to the casino, you will never see the dealer 'pick a random card from the deck' (your technique), they 'randomize the deck' (shuffle) and deal top to bottom (use an index).

Good answer. I saw shuffle in the STL docs. I'll google it. Thanks for all the help.

Good answer. I saw shuffle in the STL docs. I'll google it. Thanks for all the help.

Shuffle the deck yourself, don't use STL to do it for you. You won't always have STL so you'll need to know how to do it by hand.

commented: I always print out the deck on paper, shuffle it by hand, then I key back in the values. +7
Be a part of the DaniWeb community

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