Sorry if I fail to be clear enough or make any mistakes,
I am taking a C++ course so please go easy one me. So my code runs without errors when complied but the problem I have is the program goes into an infinite loop if you press a letter in the menu option and in your input for your answer.
Why is this and what can I do to make it run normally?
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int num1,
num2,
choice,
studentAnswer,
correctAnswer;
srand(time(0));
do
{
cout << "\n-----------------------------------\n"
<< " Math Tutor\n"
<< " M E N U\n"
<< "-----------------------------------\n";
cout << "1. Addition problem\n";
cout << "2. Subtraction problem\n";
cout << "3. Multiplication problem\n";
cout << "4. Division problem\n";
cout << "5. Quit this program\n";
cout << "------------------------------\n";
cout << "Enter your choice (1-5): ";
cin >> choice;
while (choice < 1 || choice > 5)
{
cout << "The valid choices are 1, 2, 3, "
<< "4, and 5. Please choose: ";
cin >> choice;
}
switch (choice)
{
case 1:
num1 = 1 + rand() % 500;
num2 = 1 + rand() % 500;
correctAnswer = num1 + num2;
cout << "\n\n";
cout << " " << setw(4) << num1 << endl;
cout << " +" << setw(4) << num2 << endl;
cout << " " << "----" << endl;
cout << " ";
break;
case 2:
num1 = 1 + rand() % 999;
num2 = 1 + rand() % 999;
while (num2 > num1)
num2 = 1 + rand() % 999;
correctAnswer = num1 - num2;
cout << "\n\n";
cout << " " << setw(4) << num1 << endl;
cout << " -" << setw(4) << num2 << endl;
cout << " " << "----" << endl;
cout << " ";
break;
case 3:
num1 = 1 + rand() % 100;
num2 = 1 + rand() % 9;
correctAnswer = num1 * num2;
cout << "\n\n";
cout << " " << setw(4) << num1 << endl;
cout << " *" << setw(4) << num2 << endl;
cout << " " << "----" << endl;
cout << " ";
break;
case 4:
num2 = 1 + rand() % 9;
num1 = num2 * (rand() % 50 + 1);
correctAnswer = num1 / num2;
cout << "\n\n";
cout << " " << num1 << " / " << num2 << " = ";
break;
case 5:
cout << "Thank you for using Math Tutor.\n\n";
break;
}
if (choice >= 1 && choice <= 4)
{
cin >> studentAnswer;
if (studentAnswer == correctAnswer)
cout << "\n\nCongratulations! That's right.\n\n";
else
cout << "\n\nSorry, the correct answer is " << correctAnswer
<< ".\n\n";
}
} while (choice != 5);
return 0;
}