I make a game that the user need to guess the number,
the number is generated with rand
function.
If the user wrote an invalid number or a character, print error message.
My problem is that cin.fail()
does not working well for me, for example, when I enter a character as input, my program is always printing "Too Low!", maybe because it calculates the value of the character ( ASCII TALBE ).
Any suggestions ?
My Code:
void Game()
{
srand(time(0));
int iGuess;
const unsigned int iNum = (rand() % 1000 + 1);
Start:
system("cls");
cout << "\n Guess the Num: "; cin >> iGuess;
if (iGuess == iNum) {
system("color A");
cout << "\n\n Good Job! You Won!";
exit(0);
}
if (iGuess > iNum) {
cout << "\n\n Too High!";
Sleep(3000);
goto Start;
}
if (iGuess < iNum) {
cout << "\n\n Too Low!";
Sleep(3000);
goto Start;
}
if (cin.fail()) {
cout << "Input has failed! & Error Code: " << GetLastError();
Sleep(3000);
goto Start;
}
}