-
Handling input from cin
My current project requires me to trap non-valid input (values that are not rational numbers) and return an error. The code I'm using is:
Code:
// Input the value
while (cin.fail())
{
cout << "Invalid value. Please enter a real number: ";
cin.clear();
cin.ignore(1000, '\n'); // clean buffer
cin >> values[element]; // Ask for proper input
};
However, my instructor's code is this:
Code:
// Input the value
char chrResponse;
if (cin.rdstate() != 0)
{
cin.clear();
cin >> chrResponse; // clean buffer
}
// Ask for proper input
Would both be correct, and which would be better?
-
As long as your object "value" is type float or double (real number) and you input the value prior to your while loop, your code will work (not sure why you have an array?). Your professor's code, however, will not. The code uses type char. The char will allow you to input anything and just drop everything beyond 1 character. You would be hard pressed to get this to fail. Even if this would work, the code only clears the failbit and not the buffer. I believe what the instructor was basically trying to do, is test for the fail bit using a different method:
Code:
// should use while condition instead of if in case
// of bad input more than once
while(cin.rdstate() == ios::failbit)
{
};
// basically the same as
while (cin.fail()) // looks for the bad or failbit
{
};
Basically, your code works and your instrutor's code does not. Unless there is more to it that was not shown.
David