Handling input from cin

This is a discussion on Handling input from cin within the C++ Programming forums, part of the General Programming Boards category; My current project requires me to trap non-valid input (values that are not rational numbers) and return an error. The ...

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.