Reputation: 41
I have a piece developed by me,In following i have the problem of Type Casting and exception raising:
#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);
}
So,problem here is when user enters a alphabetical value it should be caught by catch and message should be displayed but its going into infinite loop and executing the cout statements without breaking,So can any one provide me suggestion how to catch this exception and how we can restrict the user to enter digits only in C++.
Upvotes: 0
Views: 219
Reputation: 31435
By default, invalid iostream commands do not throw, but leave a failed state on the stream.
However you can get them to throw.
http://www.cplusplus.com/reference/iostream/ios/exceptions/
I am not certain whether, if this flag is set, you still have to clear the failed bit state on the iostream buffer. It is probably worth doing anyway. (cin.clear()
and cin.ignore()
)
Upvotes: 1
Reputation: 523214
cin >> s
will not cause an exception normally. It will just set the failbit()
of the cin
and any subsequent operation will fail until you clear the failbit. The proper treatment should be like
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;
}
Upvotes: 1