【发布时间】:2021-12-29 01:14:50
【问题描述】:
我的异常处理有问题。它似乎适用于负输入,但每当我尝试输入一个字符时,它就会在第一个 try/catch 块中陷入无限循环。
我尝试使用clear() 和ignore() 换成cin,但还是不行。我尝试了不同的if 语句作为输入,例如(if ((ft >100)) || (in >100)),抛出异常就好了。
我错过了什么吗?
#include <iostream>
using namespace std;
class convert
{
private:
int feet;
int inch;
public:
convert() = default;
double calculation(int ft, int in)
{
double cm = 0;
cm = ((ft * 30.48) + (in * 2.54));
return cm;
}
};
class negativeNumber
{};
class invalidInput
{};
int main()
{
int ft;
int in;
double cm = 0;
convert h;
while (true)
{
try
{
cout << "Please enter your height in (ft, in) format" << endl;
cin >> ft;
cin >> in;
if ((ft < 0) || (in < 0))
{
throw negativeNumber();
}
if (cin.fail())
{
throw invalidInput();
}
cm = h.calculation(ft, in);
cout << "Your height in cm is: " << cm << endl;
break;
}
catch (negativeNumber)
{
cout << "You entered negative numbers. Try again" << endl;
system("pause");
}
catch (invalidInput)
{
cout << "You entered a character. Try again" << endl;
system("pause");
}
}
return 0;
}
【问题讨论】:
-
这并没有解决问题,但在
cm = ((ft * 30.48) + (in * 2.54));中,您不需要任何这些括号。