0

我有一个我开发的作品,在下面我遇到了类型转换和异常引发的问题:

#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++ 中输入数字。

4

2 回答 2

1

cin >> s通常不会导致异常。它只会设置 的failbit()并且cin任何后续操作都将失败,直到您清除故障位。正确的治疗应该是这样的

while (!(cin >> s)) {   // the '!' operation checks whether the 'cin' object has failed
    // handle failure and retry
    cin.clear();   // clear failbit
    cin.ignore(INT_MAX, '\n');   // ignore invalid input.
    cout<<"please enter proper values"<<endl;
}
于 2012-10-22T10:22:57.470 回答
1

默认情况下,无效的 iostream 命令不会抛出,而是在流上留下失败状态。

但是,您可以让他们投掷。

http://www.cplusplus.com/reference/iostream/ios/exceptions/

我不确定,如果设置了这个标志,您是否仍然需要清除 iostream 缓冲区上的失败位状态。无论如何,这可能是值得的。(cin.clear()cin.ignore())

于 2012-10-22T10:20:59.380 回答