I'm starting to pull my hair out. I'm pretty new to C++, and am trying to fix a loop I have in my code. I have not been able to give the user a way to exit the program unless he/she correctly anwers the multiplication question this program asks. I'm trying to make it so that the program prompts the user to exit or continue even if the user's answer is incorrect. Any guidance you may be able to offer me would be greatly appreciated. Here is my code so far.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

//function declaration
int incorrect();

int main()
{
	srand ( time (0) ); // seeds the random number generator

	bool exit = false;

	cout << "Enter your answer to the multiplication question below and press Enter.";
	cout << endl << endl;

	while (exit != true)
	{
                  int num1 = rand() % 10;	// assigns a random number to num1
		int num2 = rand() % 10; // assigns a random number to num2
		int answer = 0;
		int correctAnswer = num1 * num2;
		bool correct = false;

		while (!correct)
		{
			cout << "What is " << num1 << " x " << num2 << "?" << endl;
			cin >> answer;

			if (answer == correctAnswer)
				correct = true;
			else
				correct = false;				
			if (!correct)
				// calls incorrect function
				incorrect();
			else
				cout << endl << "Very good!" << endl << endl;
		}// end while
		cout << "Type 1 to exit or 0 to continue." << endl;
		cin >> exit;
	}// end while
	return 0;
}// end main function

// function when the answer given is not correct
int incorrect()
{
	cout << endl << "No. Please try again!" << endl << endl;
	return 0;
}// end incorrect function

Thank you.

Mike
mike@mikeandsandra.com

> cout << "Type 1 to exit or 0 to continue." << endl;
> cin >> exit;
Put these two lines inside your inner while loop, so you ask after each response.

> while (!correct)
Change to
while (!correct && !exit)

exit is also the name of a function in cstdlib, so you might want to change the name of your local variable to save a bit of weirdness later on.

You're suggestion worked perfectly. Thanks. I appreciate it.

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.