I have this blackjack 40 assignment for my c++ class. How would i validate the input so that the user cannot type any other number or letter.
[code]
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int draw_card() {
return rand() % 13 + 1;
}
int main() {
const int BET = 10;
cout << "Please choose a random seed, or 0 to use the current time:\n";
int seed = 0;
cin >> seed;
if (seed == 0) srand(time(0));
else srand(seed);
cout << "Welcome to Blackjack-40!\n\n";
int money = 100;
int choice = 0, total = 0, dealer_total = 0, card;/
while (true) {
if (choice != 1) {
cout << "You currently have $" << money << " and are betting $" << BET << endl;
}
if (choice == 1) {
card = draw_card();
if (card >= 10) {
card = 10;
}
if (card == 1 || card == 11) {
if (total + 11 <= 40) card = 11;
else card = 1;
}
cout << "You drew a " << card << endl;
total += card;
} else {
for (int i = 0; i < 4; i++) {
card = draw_card();
if (card >= 10) {
card = 10;
}
if (card == 1 || card == 11) {
if (total + 11 <= 40) card = 11;
else card = 1;
}
cout << "You drew a " << card << endl;
total += card;
}
}
int playedHands = 0;
cout << "The total value of your cards is: " << total << endl;
if (total == 40 && playedHands == 1) {
cout << "BLACKJACK 40!" << endl;
cout << "Player wins 20 dollars" << endl;
money += 20;
if (money >= 200) {
cout << "A WINNER IS YOU! GAME OVER!\n";
return 0;
}
choice = 0;
total = 0;
continue;
} else if (total > 40)
cout << "BUSTED!" << endl;
if (total <= 40) {
cout << "Do you wish to 1) Hit or 2) Stay or 3) Quit?\n";
cin >> choice;
} else choice = 2;
if (choice == 1)
continue;
if (choice == 3)
return 0;
while (dealer_total <= 35) {
card = draw_card();
if (card >= 10) card = 10;
if (card == 1) card = 11;
cout << "Dealer drew a " << card << endl;
dealer_total += card;
}
cout << "The total value of the dealer's cards is: " << dealer_total << endl;
if (dealer_total > 40) { // && total <= 40) {
// cout << "DEALER BUSTED!" << endl;
cout << "Player wins 10 dollars" << endl;
money += 10;
}
if (dealer_total <= 40 && total > 40) {
cout << "Dealer wins 10 dollars" << endl;
money -= 10;
} else if (total <= 40 && dealer_total <= 40) {
if ((40 - dealer_total) < (40 - total)) {
cout << "Dealer wins 10 dollars" << endl;
money -= 10;
} else {
cout << "Player wins 10 dollars" << endl;
money += 10;
}
} else if (dealer_total > 40) { //or && total > 40
cout << "DEALER BUSTED!" << endl;
}
total = 0;
dealer_total = 0;
choice = 0;
if (money == 0) {
cout << "YOU LOSE! GAME OVER!\n";
return 0;
} else continue;
if (money == 200) {
cout << "A WINNER IS YOU! GAME OVER!\n";
return 0;
} else continue;
}
}