如果用户输入的选项不在1-5之间并且是一个数字,则程序按预期工作并要求他们输入正确的选项。但是,如果用户输入的数字不是数字,则程序会出现故障,并且卡住重复相同的消息,然后不允许用户输入任何内容
(https://gyazo.com/d34e78e361344a5a3c9330e28b287960)
我是编码的新手,但我认为它与我的默认情况有关,而不是我认为应该如何工作。解决这个问题的任何帮助都非常感谢。
// Create a menu with 4 options (Add, Subtract, Multiply, Divide)
// Check for divide by 0 errors
// Also add option which confirms users choice to exit the program
#include <iostream>
using namespace std;
int main()
{
float fOne, fTwo, fSum; // Two numbers that the user will input and the sum of them after selecting an option
int iOption; // Option that user will select on the menu
char cEnd; // Used for user to continue / end the program
cEnd = ('n');
do
{
cout << "Please choose an option." << "\n" << endl; // Asking user to select one of the 5 options
cout << "1: Addition." << endl;
cout << "2: Subtraction." << endl;
cout << "3: Multiplication." << endl;
cout << "4: Division." << endl;
cout << "5: Exit Program." << '\n' << endl;
cin >> iOption; // Getting user to input their option
switch (iOption)
{
case 1: cout << "Enter two numbers: " << endl; // Prompting user to enter two numbers
cin >> fOne;
cin >> fTwo;
fSum = fOne + fTwo;
cout << "The sum of your two numbers added together is: " << fSum << "\n" << endl; // Result will print to the screen depending on which option was selected
break;
case 2: cout << "Enter two numbers: " << endl;
cin >> fOne;
cin >> fTwo;
fSum = fOne - fTwo;
cout << "The sum of your two numbers subtracted from each other is: " << fSum << '\n' << endl;
break;
case 3: cout << "Enter two numbers: " << endl;
cin >> fOne;
cin >> fTwo;
fSum = fOne * fTwo;
cout << "The sum of your two numbers multiplied together is: " << fSum << '\n' << endl;
break;
case 4: cout << "Enter two numbers: " << endl;
cin >> fOne;
cin >> fTwo;
if (fTwo == 0) // If input two == 0 program will return an error message and return to menu
{
cout << "Error, cannot divide by zero. " << '\n' << endl;
}
else if (fTwo != 0) // If input two is != 0 program will calculate the sum
{
fSum = fOne / fTwo;
cout << "The sum of your two numbers divided by each other is: " << fSum << '\n' << endl;
}
break;
case 5: cout << "Are you sure that you want to exit the program?" << endl; cout << "Select an option (y/n)" << '\n' << endl; // Asking the user if they wish to exit the program and prompting them to select an option
cin >> cEnd; // User should input either y or n
if (cEnd == 'y' || cEnd == 'Y') // Inputting 'y' || 'Y' will end the program and tell the user that it is exiting
{
cout << "The program will now exit. " << '\n' << endl;
system("pause");
return 0;
}
break;
default:
cout << "Please select an option between 1-5." << '\n' << endl;
break;
}
}
while (cEnd == 'n' || 'N'); // Program will continue whilst end == 'n' or 'N', program will close if end == 'y' or 'Y'
}