Problem Creating a Game of 21

Hi all,

I'm new to C++ and I am trying to create a game of 21 as part of a project for my Computer Science. The game is supposed to assign the user two random numbers between 1 and 10, then ask if they want to hit or stay. Every time they hit, the computer gives them another random number between 1 and 10 and adds it to their total. Once they have their final number (assuming they didn't bust yet), the computer is supposed to generate it's own random number between 16 and 23. If the computer's number is over 21, the user wins. If the computer's number is 21 or lower, but greater than the user's, the computer wins.

The main problem I am having is trying to figure out how to keep generating random numbers for the user and adding them to the user's total if the user keeps asking to hit. I.e. if the user keeps getting really low numbers, they will keep asking to hit until they get close to 21. I don't know how to keep giving them random numbers without creating a bunch of if statements within each other and how to add those new numbers to their total.

Here is the section of code i have for the game so far. Any help you could give me is greatly appreciated.

bool result;
char hitOrStay;
srand(time(0));

int number1 = rand() % 10 + 1;
int number2 = rand() % 10 + 1;
cout << "Your first two numbers are " << number1 << " and " << number2 << "." << endl;
int total = number1 + number2;
cout << "Therefore your total is " << total << "." << endl;
cout << "Would you like to (H)it or (S)tay?" << endl;
cin >> hitOrStay;
if (hitOrStay == 'h' || hitOrStay == 'H') {
int number3 = rand() % 10 + 1;
cout << "The third number is " << number3 << "." << endl;
cout << "Would you like to (H)it or (S)tay?" << endl;
cin >> hitOrStay;
if (hitOrStay == 'h' || hitOrStay == 'H') {
int number4 = rand() % 10 + 1;
cout << "The fourth number is " << number3 << "." << endl;
}
else if (hitOrStay == 's' || hitOrStay == 'S') {

}
}
else if (hitOrStay == 's' || hitOrStay == 'S') {
cout << "Your total is " << total << "." << endl;
}
else
cout << "Please enter H or S." << endl;

int compNum = rand() % 8 + 16;
cout << "My total is " << compNum << "." << endl;
if (compNum > 21)
cout << "You win." << endl;
else if (compNum >= total && compNum <= 21)
cout << "You lose." << endl;
else
cout << "You win." << endl;

return result;
This section:
1
2
3
4
5
if (hitOrStay == 'h' || hitOrStay == 'H') {
		int number3 = rand() % 10 + 1;
		std::cout << "The third number is " << number3 << "." << std::endl;
		std::cout << "Would you like to (H)it or (S)tay?" << std::endl;
		std::cin >> hitOrStay;


needs to go in a loop of some kind. outside of this loop declare a 'total' int variable and everytime the user draws another card, add this value to total.
Topic archived. No new replies allowed.