0

Breaking out of do while loop??

Hello, I am not being able to get out of my do..while loop. Can someone please help? When the sum is more than 22, I want the program to break out of loop and prompt "Busted!". Thanks is advance. #include<cstdlib> #include<ctime> #include <iostream> using namespace std; int main() { int sum; char tryagain; cout<< ">" << " "<< "In the card game named 'Blackjack' players get two cards to start with, and then they are asked whether or not they want more cards. Players can continue to take as many cards as they like. Their goal is to get as close as possible to a total of 21 without going over. Face cards have a value of 10. Dealer has 18." << endl << endl; srand(time(NULL)); int card1=rand()%10+1; int card2=rand()%10+1; cout<< endl<< ">" << " " << "Your cards are"<<" " << card1<<" " << "and"<< " " << card2; sum = card1 + card2; cout << endl << ">" << " "<< "Total:"<< " " <<sum; cout << endl<< endl<< ">" << " "<< "Do you wish to pick another card? (y/n)"; cin>> tryagain; while(tryagain == 'y' ){ do{ srand(time(NULL)); int newcard = rand()%10+1; cout << ">" << " " << "New card:"<< " "<< newcard; sum+= newcard; cout <<endl << ">" << " " << "Total:" << sum<< endl; if(sum > 21){ break; } cout << endl <<">" << " " <<"Do you want to pick another card? (y/n)"; cin>> tryagain; }while(tryagain == 'y'); } if (sum == 18){ cout<< "It was a draw!"; } if(sum < 18){ cout<< "You lose!"; } if(sum > 18 && sum < 21){ cout<< "You win!"; } if(sum > 21){ cout<< "Busted!"; } return 0; }

16th Feb 2017, 10:41 PM
Safal Basnet
Safal Basnet - avatar
3 odpowiedzi
0
why using double while.. i think possible using one loop block
16th Feb 2017, 10:46 PM
전현수
전현수 - avatar
0
Even though, how do i generally break out of the loop?
16th Feb 2017, 11:18 PM
Safal Basnet
Safal Basnet - avatar
0
This is because you have nested loops. You have a do-while loop inside of a while loop. They are using the same condition to end the loop. This is redundant. When you reach your break statement you will only break out of the current inner loop (do-while) and you remain in the while loop which is then re-entering into the do-while loop until 'y' is entered. Remove the outer while loop and the code works fine (or at least how you have it programmed). Note that you don't have a condition for the player to win if the sum is 21! BTW if(sum > 18 && sum < 21) should be if(sum > 18 && sum < 22)
17th Feb 2017, 2:28 AM
ChaoticDawg
ChaoticDawg - avatar