我正在编写一个基本的随机数猜谜游戏,并且在输入非法字符时尝试对其进行一些完善,只要输入了 1-100 范围之外的数字,程序就会告诉用户和用户可以重做它,字母也是如此。但是,如果您输入 23x5,您最终会收到双重错误消息,您会同时收到字母和太高/太低,具体取决于随机数。我如何对其进行排序,以便该条目也将出现在字母错误消息下?
这是我的代码: Header.h
#ifndef HEADER_H
#define HEADER_H
int nGuessedNumber;
int nNumberOfGuesses = 1;
int nRandomNumber;
int UserInput();
#endif
源.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
extern int nGuessedNumber;
int UserInput()
{
while(!(cin >> nGuessedNumber))
{
cin.clear();
while(cin.get() != '\n'){}
cout << "I asked for a number between 1 and 100.\n";
}
return nGuessedNumber;
}
主文件
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Header.h"
using namespace std;
int main()
{
srand(time(0));
nRandomNumber = rand() % 100 + 1;// sets random number between 1 and 100
cout << "Guess a number from 1 too 100: " << endl;
UserInput();
while (nGuessedNumber != nRandomNumber)
{
if ((nGuessedNumber < 1) || (nGuessedNumber > 100))
{
cout << "Oi! Between 1 and 100!\n";
UserInput();
}
else
{
if (nGuessedNumber < nRandomNumber)
{
for (nGuessedNumber; nGuessedNumber < nRandomNumber; nNumberOfGuesses++)
{
cout << "Too low, try again!" <<endl;
UserInput();
}
}
else if (nGuessedNumber > nRandomNumber)
{
for (nGuessedNumber; nGuessedNumber > nRandomNumber; nNumberOfGuesses++)
{
cout << "Too high, try again!"<< endl;
UserInput();
}
}
}
}
if (nGuessedNumber == nRandomNumber)
{
cout << "Congratulations! " << nGuessedNumber << " is correct!" << endl;
cout << "You guessed " << nNumberOfGuesses << " times." << endl;
}
system("PAUSE");
return 0;
}