# Guessing Numbers

## Problem

• Write a program in which the computer picks a random number between 1 and 100.
• Then as long as the user has not guessed the correct number, let the user guess a number and report whether their guess is too high or too low.
• Then print the random number

• Modify the “Guessing Numbers” program so that when one game has ended, the user is asked if they want to play again.
• Play should continue until the user responds “no” to the prompt to play again

## Solution

/*
Test case 1:
Input: User guesses -1 (not an integer you'd normally expect)
Expected Output: Too low
Actual Output: Too low

Test case 2:
Input: User guesses "BBQ sauce" (not an integer at all)
Expected Output: Reprompt the user
Actual Output: reprompts the user

Test case 3:
Input: User guesses 50 (valid number)
Expected Output: Too low or too high
Actual Output: Varied appropriately

*/

#include <iostream>
#include <ctime>
#include <string>

using namespace std;

const int MIN_RAND_NUM = 0;
const int MAX_RAND_NUM = 100;

int main()
{
// inputs: user guesses
// outputs: too high/low, computer's number

//This must be defined outside the loop in order to use it in the loop condition, but it is modified in the loop.
string input;

// This is the loop around the whole program
do
{
// Computer picks a random number
srand(time(0)); // Make rand() generate random and not pseudorandom numbers
int random_number = rand() % (MAX_RAND_NUM - MIN_RAND_NUM + 1) + MIN_RAND_NUM;

// uncommenting the following line would give away the computer's random number!
// cout << "My random integer is " << random_number << endl;

int user_input = -1;

// Let the user start guessing
do
{
// Each loop executes one guess
cout << "Gimme your best shot: ";
cin >> user_input;

while (cin.fail()) // tried to read an integer, but found something else in cin buffer
{
cout << "That's bad. Gimme another: ";
string dummy_input; // used to consume bad input that's sitting in cin
cin.clear(); // clears the "red light" on cin that's telling me there's a problem
cin >> dummy_input; // consumes bad input that's sitting in cin
cin >> user_input; // waits for new input
}

if (user_input < random_number)
{
cout << "TOO LOW!" << endl;
}
else if (user_input > random_number) // simply using an else here would not work. Why not?
{
cout << "TOO HIGH!" << endl;
}

} while (user_input != random_number);
// until he/she gets the random number

// Print out the random number
cout << "That's right! My number was " << random_number << "!" << endl;

cout << "Play again (Y/N) :)?" << endl;
cin >> input;
} while (input == "Y");

system("pause");
return 0;
} 