Question: The following code goes on a loop when I input a letter, how can I stop the loop using exceptions in C++ #include #include using
The following code goes on a loop when I input a letter, how can I stop the loop using exceptions in C++
#include
#include
using namespace std;
const double centimeterToInches = 2.54;
const int footToInches = 12;
int main()
{
int feet;
int inches;
int totalInches;
double centimetre;
bool done = false;
string negativeInput = "Invalid... Do not enter negative or non-digit numbers, Please enter another set of numbers";
do
{
try
{
cout << "Enter the length in feet: ";
cin >> feet;
if (feet <= 0)
throw negativeInput;
cout << "enter the length in inches: ";
cin >> inches;
if (inches <= 0)
throw negativeInput;
else if (isalpha(feet) != 0 || isalpha(inches) != 0)
throw negativeInput;
done = true;
totalInches = footToInches*feet + inches;
centimetre = centimeterToInches*totalInches;
cout << "The length in centimeters is:" << centimetre << endl;
}
catch (string inputerror)
{
cout << inputerror << endl;
cin.clear();
}
} while (!done);
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
