Simple question (involving rand() i think)
I'm making a black jack program as an excersize (mostly in structures and such) and i'm having a problem with the deal() method.
the problem seems to be that a) the random number seems to be 13 all the time ('k' is the output twice) and after i enter anything for the cin, it gives me a bus error and quits. any ideas?
(the player struct has a few ints (money, bet) and the name and hand (a 2-element array) for the player.)
this is the code for that method:
void deal(person player)
{
int i;
char askhit[3];
cout<<"You got: ";
for(i = 0; i < 3; i++) {
player.hand[i] = (rand()%13 + 1);
if (player.hand[i] == 11) player.hand[i] = 'j';
if (player.hand[i] == 12) player.hand[i] = 'q';
if (player.hand[i] == 13) player.hand[i] = 'k';
cout<<player.hand[i]<<" ";
}
cout<<endl;
do {
cout<<"Would you like to hit?"<<endl;
cin>>askhit>>endl;
if (askhit[0] == 'y' || askhit[0] == 'Y') hit(player);
} while (askhit[0] == 'y' || askhit[0] == 'Y');
}
Is there any need to shuffle?
Haven't written card games since Uni. Anyway, this is how I used to do it.
Code:
// Declare a deck of cards
const int VALMAX = 13; // 14 for some European sets
const int SUITMAX = 4;
const int DECKMAX = VALMAX * SUITMAX;
int deck[DECKMAX];
// Initialize the deck
remain = DECKMAX;
for (int i = 0; i < remain; i++)
deck[i] = i;
// Deal the next one
int choice = rand () % remain;
card = deck[choice];
// replace the chosen card with the last card in the remaining deck
remain--;
deck[choice] = deck[remain];
// Decoding
int value = card % VALMAX;
int suit = card / VALMAX;
It is sort of inline shuffling.