Protecting very basic game from input error overload
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
//returns value between 0 and RAND_MAX
//rand();
//srand (time(0));
int main(){
int x,w,random,guess,tries;
char play;
cout << "Welcome to Guess It, the number guessing game.\n";
do {
cout << "\nEnter a difficulty level:\n1. Easy\n2. Medium\n3. Hard\n4. Very Hard\n5. Insane!\n\n";//States possible difficulties
cin >> w;
if (w==1) x = 50;
if (w==2) x = 100;
if (w==3) x = 500;
if (w==4) x = 1000;
if (w==5) x = 10000;//Determines upper limit for random generator
srand(time(0));//Random seed
random = rand() % x + 1;//Random number generation
cout << "\nNumber chosen between 1 and " << x << ".\n";
cout << "Enter your guess.\n";
cin >> guess;
tries = 1;//Sets tries to one after first guess before going into the game loop
while (guess != random){
if (guess > x){
cout << "\nIllegal guess. Your guess must be between 1 and " << x << ".\n";//Keeps player from inputting a number that is not available
--tries;//Sets counter back to keep track of legal guesses only
}
else if (guess < 1){
cout << "\nIllegal guess. Your guess must be between 1 and " << x << ".\n";//SAA
--tries;//SAA
}
else if (guess > random)
cout << "\nYou guessed too high.\n";
else
cout << "\nYou guessed too low.\n";//The actual process of guessing the number
cout << "Enter your guess.\n";
cin >> guess;
++tries;
}
cout << "\nYou Guessed It!\n";
cout << "You took " << tries << " guesses.\n";//Displays number of legal guesses required to win the round
cout << "Would you like to play again (Y/N)?\n";//Asks if player wants to play again, feeds into do...while loop parameter
cin >> play;
} while (play == 'y');
return 0;
}
Now, right at the beginning of the game loop, I wanted to put something to test if the input was an integer at all. I read in a few places that I could use "cin.good()" to determine that by basically putting
if (cin.good() == false)
or
if (!cin.good())
and the whole selection would be:
if (cin.good() == false){
cout << "\nIllegal guess. You must guess a number.\n";
--tries;
}
Now, you would think this would work. However, when I put that in and test in in the running the program, it starts an infinite loop outputting the "Illegal guess" line , over and over again, never allowing me to give another input. I can't stop it except by closing the program. Anyone have any ideas?

