我有一个我开发的作品,在下面我遇到了类型转换和异常引发的问题:
#include <iostream>
#include <string>
#include <exception>
using namespace std;
class WithdrawlCheck
{
int Balance;
int amount;
string s;
public:
void CheckBalance()
{
cout<< "Sorry,You don't have Balance to Perform this transaction";
}
void WithdrawlCash(int Balance)
{
if(Balance<500)
{
//cout<< "Sorry,You don't have Balance to Perform this transaction";
CheckBalance();
}
else
{
cout<<"enter the amount to withdrawl only in digits"<<endl;
try
{
cin>>amount;
}
catch(exception c)
{
cout<<"please enter proper values"<<endl;
WithdrawlCash(Balance);
}
if(Balance>amount)
{
Balance=Balance-amount;
cout<<"Your current Balance is:"<<Balance<<endl;
}
else{
cout<<"Insufficient Balance";
}
}
cout<<"do you want to Perform More Transaction,Say Y/N"<<endl;
cin>>s;
int num=s.compare("exit");
int n1=s.compare("Y");
int n2=s.compare("y");
if(num==0||n1==0||n2==0)
{
WithdrawlCash(Balance);
}
else
{
cout<<"Bye";
exit(0);
}
}
};
int main()
{
int Bal;
cout<<"**********"<<"Welcome User"<<"*********"<<endl;
cout<<"Enter the Balance"<<endl;
cin>>Bal;
WithdrawlCash c;
c.WithdrawlCash(Bal);
}
所以,这里的问题是当用户输入一个字母值时,它应该被 catch 捕获并且应该显示消息,但是它会进入无限循环并执行 cout 语句而不会中断,所以任何人都可以给我建议如何捕获这个异常以及如何我们可以限制用户只能在 C++ 中输入数字。