Problem with program getting stuck in an endless loop.

I've been having trouble with this program I've been working on and the problem happens when you enter a letter into an integer variable.

The program actually works pretty well and does what I want it to do which is ask a multiplication question and ask the user to try again if their wrong or ask a new question if their right.

The problem comes when the user enters a letter (or a decimal)instead of a number for their answer. I thought the 'else' statement would take care of any answer that wasn't correct, but it only works for incorrect integers. If you enter a non-integer as the answer the program will output:

WRONG!

Try Again...

What is numA X numB?

...in an infinite loop until I close the console window.


I only posted the part of my program that has the problem below. I also put where I am pretty sure the problem areas are in bold.

If anyone has an idea as to whats wrong please let me know how I can fix it.



#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

bool Question(int, int, int);
bool Exit();

int main()
{
srand(time(0));

bool Esc = 0;
int Try = 0;
int Answer = 0;
int numA = (rand() % 10);
int numB = (rand() % 10);



while(Esc != 1)
{

std::cout << "What is: " << numA << " X " << numB << "\n";
std::cin >> Answer;

if (Question(Answer, numA, numB))
{
std::cout << "\nCORRECT! Well Done.\n";
numA = (rand() % 10);
numB = (rand() % 10);
Try++;
}

else
{
std::cout << "\nWRONG!\n\n";
std::cout << "Try Again...\n\n";
}


if(Try%6 == 5)
Esc = Exit();

}

system("pause");

return 0;
}

bool Question(int Answer, int numA, int numB)
{

if (Answer == (numA * numB))
return 1;

else
return 0;
}
hi,

if you add the following you should get away from the endless loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

                std::cout << "What is: " << numA << " X " << numB << "\n";

		std::cin >> Answer;

		if (std::cin.fail())                   //new code start
		{
			std::cin.clear();
			std::cin.ignore(1);

			continue;
		}                                      //new code end


		if (Question(Answer, numA, numB))
		{
			std::cout << "\nCORRECT! Well Done.\n";
			numA = (rand() % 10);
			numB = (rand() % 10);
			Try++;
		}


What this code does is ignore the bad input and restart your input code

Hope This has helped
Shredded
Topic archived. No new replies allowed.