-
cin.fail
can someone tell me why this cin.fail statement will not work.
thanks
Code:
#include <iostream>
using namespace std;
double balance;
double charge(double charge_amount);
double payment(double pay_amount);
void quit();
void display();
int main()
{
char trans;
double chargeAmt;
double payAmt;
cout<<"Enter beginning balance. ";
cin>>balance;
cout<<endl;
do
{
cout<<"Enter transaction.(C,P,D,Q) ";
cin>>trans;
cout<<endl;
if (trans == 'C' || trans == 'c')
{
cout<<"Enter amount of charge. ";
cin>>chargeAmt;
if (cin.fail())
{
cout<<"ERROR: Bad input!";
return 1;
}
charge(chargeAmt);
cout<<"Your new balance is "<<balance;
cout<<endl;
}
else if (trans == 'P'|| trans == 'p')
{
cout<<"Enter payment. ";
cin>>payAmt;
payment(payAmt);
cout<<"Your new balance is "<<balance;
cout<<endl;
}
else if (trans == 'D' || trans == 'd')
{
display();
}
else if (trans == 'Q' || trans == 'q')
{
quit();
}
else
cout<<"Not Valid";
cout<<endl;
}
while (trans != 'Q');
return 0;
}
double charge (double charge_amount)
{
balance = balance + charge_amount;
return balance;
}
double payment(double pay_amount)
{
balance = balance - pay_amount;
return balance;
}
void display()
{
cout<<"Your balance is "<<balance;
cout<<endl;
}
void quit()
{
cout<<"Good Bye!";
cout<<endl;
}
-
It works as I expected. It 's just probably not what you expected.
Input: 100 -> no error msg
Input: kkk -> error msg
Input: 100k -> no error msg, because it only reads the '100' and 'k' is left in the stream for another input method to fetch. I suppose you want this kind of input to give error message, so what you need to is, not sure, but read the input as a string and make sure all characters in the string are digits.
-
i am wanting it to only take in numbers as input and give an error message for anything else.
-
Try getline() then check the input instead.