I have been trying to incorporate a check to see if the input from the user is a valid input. For example my program wants the user to guess a number between 1-1000. My program works perfectly, except when the user inputs any other character other than a number it goes CRAZY. Anyways, I want it to check and make sure that the user is inputting numbers, not something silly. So I have been going in circles trying to figure this part out. I am sure it is a easy fix, but I am new to programming and this has got me stumped. Any help would be appreciated.
#include "stdafx.h"
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
bool isGuessed=true;
while(isGuessed)
{
srand(time(0));
int number=rand()%1000+1;
int guess;
char answer;
cout<<"Midterm Exercise 6\n";
cout<<"I have a number between 1 and 1000.\n";
cout<<"Can you guess my number?\n";
cout<<"Please type your first guess:\n\n";
cin>>guess;
while(guess!=number)
{
if(guess>number)
{
cout<<"\nToo high. Try again!\n\n";
cin>>guess;
}
if(guess<number)
{
cout<<"\nToo low. Try again!\n\n";
cin>>guess;
}
}
if(guess==number)
{
cout<<"\nExcellent! You have guess the number!\n";
}
cout<<"Would you like to play again (y or n)?\n\n";
cin>>answer;
cout<<"\n";
if(answer!='y')
{
isGuessed=false;
cout<<"Thanks for playing!\n\n";
system ("PAUSE");
return 0;
}
}
return 0;
}