I am making a simple guess the number game using C++. My program checks if the user input is an integer or not. But when I input for example "abc" the program keeps saying: "Input a number!" instead of saying it once and let the user input something again..
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int chances = 3;
void ask();
void checkAnswer(int ans);
void defineNumber();
int correctAnswer;
void defineNumber(){
srand(time(0));
correctAnswer = rand()%11;
}
void checkAnswer(int ans){
if(ans == correctAnswer){
cout << "The answer was right!\n" << endl;
exit(0);
}else{
if(chances > 0){
cout << "Wrong answer, try again!\n" << endl;
chances--;
ask();
}else{
cout << "You lost!" << endl;
exit(0);
}
}
}
void ask(){
int input;
cout << correctAnswer << endl;
try{
cin >> input;
if(input > 11 || input < 0){
if(!cin){
cout << "Input a number!" << endl; //HERE LIES THE PROBLEM
cin.clear(); //I TRIED THIS BUT DIDN'T WORK AS WELL
ask();
}else{
cout << "Under 10 you idiot!" << endl;
ask();
}
}else{
checkAnswer(input);
}
}catch(exception e){
cout << "An unexpected error occurred!" << endl;
ask();
}
}
int main(){
cout << "Welcome to guess the number!" << endl;
cout << "Guess the number under 10: ";
defineNumber();
ask();
}
Thanks in advance.