我一直在尝试合并检查以查看用户的输入是否是有效输入。例如,我的程序希望用户猜测 1-1000 之间的数字。我的程序运行良好,除非用户输入除数字以外的任何其他字符时,它会变得疯狂。无论如何,我希望它检查并确保用户输入的是数字,而不是愚蠢的东西。所以我一直在兜圈子试图弄清楚这部分。我确信这很容易解决,但我是编程新手,这让我很困惑。任何帮助,将不胜感激。
#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;
}