#include <iostream>
#include <ctime>
#include <cstdlib>
int game_rePlay();
int hi_Lo_Game ()
{
usingnamespace std;
int userMaxRand; int userLowRand; int userGuess; int xRand; int xtries = 7;
//// Intro to game and input
cout << "Hi Lo Game" << endl;
cout << "Lets Play a game. I'm Thinking of a number. You have 7 tries " <<endl;
cout << "Enter your Lo number : # ";
while(!( cin >> userLowRand))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Enter your Lo number again : # ";
}
cout << "Enter your Hi number : # ";
while ( !(cin >> userMaxRand ))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Enter your Hi number again : # ";
}
//USER GUESES RANDOM NUMBER HERE
cout << "Guess a number between " << userLowRand << " and " << userMaxRand << " : " <<endl;
srand(static_cast<int>(time(0)));
xRand = rand() % userMaxRand + userLowRand;
// check if guess correct
while (cin >> userGuess)
// note: At this point the program ends if the input is not an integer
{
if (userGuess < xRand) {
cout << "You guessed too low, Try again: "<< endl;
}
elseif (userGuess > xRand){
cout << "you guessed too high, Try again: " <<endl;
}
cout << "Tries left : " << --xtries << endl;
switch (xtries) {
case 0:
cout << "\nSorry, You Lost.The correct number was " << xRand << "." << endl;
return game_rePlay();
}
if (userGuess == xRand) {
cout << "Correct! You win!" <<endl;
return game_rePlay();
}
}
//END OF GAME
return xRand;
}
int game_rePlay(){
usingnamespace std;
cout << "Do you want to play again ? (Y/N)" <<endl;
char replay;
while ((cin >> replay ))
{
if ( ((replay == 'y') ) || ( (replay == 'Y') ) )
{
cout<< "\n\n";
return hi_Lo_Game();
}
elseif ( ((replay == 'n')) || ((replay == 'N')) ){
cout<< "\n\n";
cout << "Thank You for playing." <<endl;
return 0;
}
else{
cout << "invalid input " <<endl;
return game_rePlay();
}
return 0;
}
//END OF GAME_REPLAY
return replay;
}
while (cin >> userGuess)
// while input extraction is successful,
{
//additional code to solve problem.
// deal with unsucessful input extraction
if(cin.fail())
{
cout << "Invalid input"<<endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (userGuess < xRand) {
cout << "You guessed too low, Try again: "<< endl;
}
So.. the only way the body of the while loop is entered into is when an input extraction is successful. But, in the body of the loop you attempt to deal with a failed input extraction.