Hello Daniweb,

I'm obviously very new to the programming world. I'm trying to make the popular Guessing random numbers game. The things I'm having a hard time with is getting the input validation to work. When characters are input instead of numbers, the program goes into an infinite loop. I'm not sure how to fix it, I've spent the last couple days searching the web and my textbook for some answers. I've tried putting it in, to no avail.

Also, I need to do the following:

· Move the guess response (the part that determines if the guess is too high or too low) functionality into a function that you write. The function must have the prototype int ReviewGuess(int, int), where the function takes the random number generated by the computer as the first parameter and the number guessed by the user as the second parameter. If the numbers match, the function will return a value of zero. If the number is too high, the function will return a value of 1. If the number is too low, the function will return a value of -1. If the user entry is not a valid value, return -2.

· Replace this code in the body of your program with a switch statement. When the user successfully guesses the number, prompt if he or she wants to play again. If so, have the computer choose a new random number.

Here is the code I have so far. The program compiles and runs fine, unless someone enters a charaacter instead of an integer.

#include <iostream>  // Used to produce input and output information.
#include <cstdlib>  // This header is used to produce the random number generator function.
#include <ctime>  // Header used to help with the production of random numbers.
#include <limits> // Header used to help with setting limits to what kind of inputs are allowed

using namespace std;  // Allows the use of cout and cin without having to type std in front of them everytime.
 
int main ()
{
	bool playAgain=true;
	while(playAgain)
	{
    int secretRandom = 0, userGuess = 0; // 
    const int MAX = 100, MIN = 1;  // Sets limits on the random number generator and the range of guesses allowed by the user.
	
	// Create random number

    srand(time(NULL)); // Part one of random number generator.
    secretRandom = (rand() % (MAX - MIN + 1)) + MIN; // Part two of random number generator.

    cout << "Welcome to My Number Generator Game" << endl; // output
	cout << "The object of the game is to guess a number between 1 and 100" << endl << endl; // output

	// Loops forever until user finds the number

	while (userGuess != secretRandom)
		{
	
        cout << "Please enter your guess : " ; // output
        cin >> userGuess;  // Input - User to enter a guess between 1 and 100
		
		cin.ignore(numeric_limits<int>::max(), '\n');

		if (!cin || cin.gcount() != 1)
		{
			cout << "ERROR!! Please enter a NUMBER between 1 and 100" << endl;
			cin.clear();			
		}
		else
		{		
			if (secretRandom < userGuess)
			{
				cout << "Your guess of " << userGuess << " is too high.  Please guess a LOWER number." << endl << endl; // output
			}
			else if (secretRandom > userGuess)
			{
			cout << "Your guess of " << userGuess << " is too low.  Please guess a HIGHER number." << endl << endl; // output
			}
			else
			{
				cout << " Congratulations, you are CORRECT with your guess of " << userGuess << " !" << endl << endl; // output
			}
		}
	}

		// This next section gives the user the opportunity to play again

		char again;
		cout << " Do you want to play again?  Enter y or n: " << endl;
		cin >> again;

		if(again!='y')
		{
			playAgain = false;
			cout << endl << " Thank you for playing My Number Generator Game! " << endl << endl; 
		}
	
     }

    char yourName;
	cout << "Please type your first name and press enter." << endl << endl; // output
	cin >> yourName; // Input - User to enter in their first name
	cin.clear();
	cin.ignore();

	return 0;

}

Recommended Answers

All 6 Replies

Quick suggestion, running out the door so i can't give a more detailed explanation. Look into CCTYPE Header. It has functions built in that should help you. If one of the functions returns false then use exit(EXIT_FAILURE) from the <cstdlib> header.

>> is simply a function call, which can fail.

So check if the cin >> userGuess succeeded or not:

if( ! (cin >> userGuess) )
   // not an integer, do something

(the () around cin >> userGuess are important.)

Ok, so I created a new function and I inserted a switch statement into the main function. The program compiles, but doesn't do anything like I want it to. Can anyone nudge me in the right direction please?

#include <iostream>  // Used to produce input and output information.
#include <cstdlib>  // This header is used to produce the random number generator function.
#include <ctime>  // Header used to help with the production of random numbers.

using namespace std;  // Allows the use of cout and cin without having to type std in front of them everytime.

int ReviewGuess(int secretRandom, int userGuess)
{
	if (secretRandom == userGuess)
		return 0;
	else if (secretRandom < userGuess)
		return 1;
	else if (secretRandom > userGuess)
		return -1;
	else if (userGuess < 1 || userGuess > 100)
		return -2;
	else
		return -2;
}

int main ()
{
	bool playAgain=true;
	while(playAgain)
	{
		int secretRandom = 0;
		int userGuess = 0;
		const int MAX = 100, MIN = 1;  // Sets limits on the random number generator and the range of guesses allowed by the user.
		// Create random number
		srand(time(NULL)); // Part one of random number generator.
		secretRandom = (rand() % (MAX - MIN + 1)) + MIN; // Part two of random number generator.
		cout << "Welcome to My Number Generator Game" << endl; // output
		cout << "The object of the game is to guess a number between 1 and 100" << endl << endl; // output
		// Loops forever until user finds the number
		while (userGuess != secretRandom)
		{
			cout << "Please enter your guess : " ; // output
			cin >> userGuess;  // Input - User to enter a guess between 1 and 100
		}

	ReviewGuess;

	switch (userGuess)
	{
	case 0:
		cout << " Congratulations, you are CORRECT with your guess of " << userGuess << " !" << endl << endl;
	case 1:
		cout << "Your guess of " << userGuess << " is too high.  Please guess a LOWER number." << endl << endl;
	case -1:
		cout << "Your guess of " << userGuess << " is too low.  Please guess a HIGHER number." << endl << endl;
	case -2:
		cout << "ERROR!! Please enter a NUMBER between 1 and 100." << endl << endl;
	default:
		cout << "Your guess is not within the guidelines of this game.  Please enter a NUMBER between 1 and 100." << endl << endl;
	}

	char yourName;
	cout << "Please type your first name and press enter." << endl << endl; // output
	cin >> yourName; // Input - User to enter in their first name
	cin.clear();
	cin.ignore();

	return 0;
	}
}

The program compiles, but doesn't do anything like I want it to

Help us out here:
- What do you want it to do?
- What does it do instead?

Sorry thelamb. I remarked what I need it to do in my first post at the top of the thread.

The first time I posted the code, it did what it was supposed to do except for an infinite loop problem when a user input a letter instead of numbers. Also, the first time I posted the code, it wasn't in the right format. For this week, the code is supposed to have a function that I created, and a switch statement in the main function to report whether the guess is high, low, correct, or an error.

At this time, with the code in somewhat the correct format, the only thing it does right is compile without errors. It asked for input of a number, but doesn't tell the user whether the number is any of the above.

Thanks for looking at it!!

I got my code to work the way I wanted it to. Now its time for the next change to it. I need to add functionality to store the guesses the user makes in an array up to a maximun number of guesses stored in a constant. It must display a list of the previous guesses before the user guesses a number each time (excluding their first guess). Once the user reaches the max number of guesses i must display a message and end the loop.

Here is my current code:

#include <iostream>  // Used to produce input and output information.
#include <cstdlib>  // This header is used to produce the random number generator function.
#include <ctime>  // Header used to help with the production of random numbers.

using namespace std;  // Allows the use of cout and cin without having to type std in front of them everytime.

int ReviewGuess(int secretRandom, int userGuess) // Function I created to check against certain conditions.
{
	if (cin.fail ()) // This "IF" statement rules out entries that do not follow the rules of the games.
	{
		cin.clear();
		cin.ignore(100,'\n');
		return -2;
	}
	else if (userGuess < 1 || userGuess > 100) // This "ELSE IF" statement keeps integer guesses between 1 and 100.
		return -2;
	else if (secretRandom == userGuess)  // this "ELSE IF" statement checks if the users guess matches the random number.
		return 0;
	else if (secretRandom < userGuess)  // This  "ELSE IF" statement checks if the user guess is higher than the random number.
		return 1;
	else if (secretRandom > userGuess)  // This  "ELSE IF" statement checks if the user guess is lower than the random number.
		return -1;
	
}

int main ()
{
	bool playAgain=true;  // Boolean expression used to offer the ability to play the game again.
	while(playAgain)
	{
		int secretRandom = 0;
		int userGuess = 0;
		const int MAX = 100, MIN = 1;  // Sets limits on the random number generator and the range of guesses allowed by the user.
		// Create random number
		srand(time(NULL)); // Part one of random number generator.
		secretRandom = (rand() % (MAX - MIN + 1)) + MIN; // Part two of random number generator.
		cout << "Welcome to My Number Generator Game" << endl; // output
		cout << "The object of the game is to guess a number between 1 and 100" << endl << endl; // output
		// Loops forever until user finds the number
		while (userGuess != secretRandom)
		{
			cout << "Please enter your guess : " ; // output
			cin >> userGuess;  // Input - User to enter a guess between 1 and 100
			int returnValue;

			returnValue=ReviewGuess(secretRandom, userGuess);

		switch (returnValue)  // Switch statement with the directions for the user, based on the users guess.
			{
			case 0:
				cout << " Congratulations, you are CORRECT with your guess of " << userGuess << " !" << endl << endl;
				break;
			case 1:
				cout << "Your guess of " << userGuess << " is too high.  Please guess a LOWER number." << endl << endl;
				break;
			case -1:
				cout << "Your guess of " << userGuess << " is too low.  Please guess a HIGHER number." << endl << endl;
				break;
			case -2:
				cout << "ERROR!! Please enter a NUMBER between 1 and 100." << endl << endl;
				break;
			default:
				cout << "Your guess is not within the guidelines of this game.  Please enter a NUMBER between 1 and 100." << endl << endl;
			}
		
		}
		// This next section gives the user the opportunity to play again

		char again;
		cout << " Do you want to play again?  Enter y or n: " << endl;
		cin >> again;

		if(again!='y')
		{
			playAgain = false;
			cout << endl << " Thank you for playing My Number Generator Game! " << endl << endl; 
		}
			
	}
	char yourName;
			cout << "Please type your first name and press enter." << endl << endl; // output
			cin >> yourName; // Input - User to enter in their first name
			
		return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.