Summary
In this lab, you will make additions to a C++ program that is provided. The program is a guessing game. A random number between 1 and 10 is generated in the program. The user enters a number between 1 and 10, trying to guess the correct number.

If the user guesses correctly, the program congratulates the user, and then the loop that controls guessing numbers exits; otherwise, the program asks the user if he or she wants to guess again. If the user enters a "Y", he or she can guess again. If the user enters "N", the loop exits. You can see that the "Y" or an "N" is the sentinel value that controls the loop.

Note that the entire program has been written for you. You need to add code that validates correct input, which is "Y" or "N", when the user is asked if he or she wants to guess a number, and a number in the range of 1 through 10 when the user is asked to guess a number.

Instructions
Ensure the source code file named GuessNumber.cpp is open in the code editor.

Write loops that validate input at all places in the code where the user is asked to provide input. Comments have been included in the code to help you identify where these loops should be written.

Execute the program by clicking the Run button. See if you can guess the randomly generated number. Execute the program several times to see if the random number changes. Also, test the program to verify that incorrect input is handled correctly. On your best attempt, how many guesses did you have to take to guess the correct number?

// GuessNumber.cpp - This program allows a user to guess a number between 1 and 10.
// Input: User guesses numbers until they get it right
// Output: Tells users if they are right or wrong

#include
#include
#include
#include
using namespace std;

int main()
{

int number; // Number to be guessed
int userNumber; // User's guess
string keepGoing; // Contains a "Y" or "N" determining if the user wants to continue

// This is the work done in the detailLoop() function
srand((unsigned)time(NULL));
number = (rand() % 10) + 1; // Generate random number

// Prime the loop
cout << "Do you want to guess a number? Enter Y or N: ";
cin >> keepGoing;

// Validate input




// Enter loop if they want to play
while(keepGoing == "Y")
{
// Get user's guess
cout << "I'm thinking of a number. .\n Try to guess by entering a number between 1 and 10: ";
cin >> userNumber;
// Validate input



// Test to see if the user guessed correctly
if(userNumber == number)
{
keepGoing = "N";
cout << "You are a genius. That's correct!";
}
else
{
cout << "That's not correct. Do you want to guess again? Enter Y or N: ";
cin >> keepGoing;
// Validate input



}
} // End of while loop
return 0;
} // End of main()



Answer :

Other Questions