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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cmath>
//got rid of this and instead just prefix all the std members with "std::" minus the quotes
//organized your function prototypes based on return value
void draw_a_card();
int rand_0toN1(int n);
int select_next_available(int n);
int cards_remaining = 52;
bool card_drawn[52];
//organized your arrays and removed the unecessary size declaration: it automatically determines the size when there's elements in it.
char *suits[] =
{
"hearts",
"diamonds",
"spades",
"clubs"
};
char *ranks[] =
{
"ace", "two", "three", "four", "five",
"six", "seven", "eight", "nine",
"ten", "jack", "queen", "king"
};
//added spacing between lines and refactored some things
int main()
{
srand(time(NULL));
int n;
std::string input;
while(1) //this is all typesafe now and it won't go into an infinite loop if you enter in invalid input
{
std::cout << "Enter no. of cards to draw (0 to exit): ";
std::getline(std::cin, input);
std::stringstream ss(input);
ss >> n;
if(n == 0)
break;
for(int i = 1; i <= n; i++)
{
draw_a_card();
}
std::cin.clear();
}
return 0;
}
void draw_a_card()
{
int r, s;
int n, card;
n = rand_0toN1(cards_remaining--);
card = select_next_available(n);
r = card % 13;
s = card / 13;
std::cout << ranks[r] << " of " << suits[s] << std::endl; //i prefer '\n' but it's up to you. 'endl' also flushes the buffer.
}
int select_next_available(int n)
{
int i = 0;
while(card_drawn[i])
{
i++;
}
while(n-- > 0)
{
i++;
while(card_drawn[i])
{
i++;
}
}
card_drawn[i] = true;
return i;
}
int rand_0toN1(int n)
{
return rand() % n;
}
|