I'm doing a conversion program where a user enters 2 values (using cin) for feet and inches, then the program converts the feet and inches to centimeters.
So I am using exception handling to handle negative number and non digit entries. I'm using a do while loop to re ask the user to input, but for some reason the program is sometimes (not all the time) endlessly looping after a character is entered. Can anyone see why it keeps doing that?
Many thanks in advance!
main
#include <iostream>
#include <iomanip>
#include "inputMismatch.h"
using namespace std;
double convert(int f,int i)
{
double cmFoot = static_cast<double>(f) * 30.48;
double cmInch = static_cast<double>(i) * 2.54;
double converted = cmFoot + cmInch;
return converted;
}
int main()
{
int feet,inches;
double centimeters;
bool done = false;
string str = "The input stream is in the fail state.";
do
{
try
{
cout << "Please enter a length in feet and inches separated by a space,\nand I will convert that length to centimeters!" << endl;
cin >> feet >> inches;
cout << endl;
if(feet < 0 || inches < 0)
throw inputMismatch(feet,inches);
if(!cin)
throw str;
done = true;
centimeters = convert(feet,inches);
cout << fixed;
cout << setprecision (2) << "Value in centimeters equal to : " << centimeters << endl;
}
catch(inputMismatch inputMismatchObj) //catch negative number exception, nondigit number exception
{
cout << "Error : " << inputMismatchObj.what() << endl;
}
catch(string messageStr)
{
cout << messageStr << endl;
cout << "Restoring the input stream." << endl;
cin.clear();
cin.ignore(100, '\n');
}
}while(!done);
system("PAUSE");
return 0;
}
exception class
#include <iostream>
#include <string>
using namespace std;
class inputMismatch
{
public:
inputMismatch()
{
message = "Unknown error occurred on input"; //no argument constructor to handle unknown exception
}
inputMismatch(int i,int j)
{
message = "Negative Number Input"; //int exception occurs, initialize appropriate error message
}
inputMismatch(int k)
{
message = "Non-Digit Number Input"; //string exception occurs, initialize appropriate error message
}
string what() //what function returns error message
{
return message;
}
private:
string message;
};

New Topic/Question
Reply


MultiQuote



|