Meaning of cin.fail() in C++?
Solution 1
cin.fail()
tells you if "something failed" in a previous input operation. I beleive there are four recognised states of an input stream: bad
, good
, eof
and fail
(but fail
and bad
can be set at the same time, for example).
cin.clear()
resets the state to good
.
while(cin.get() != '\n') ;
will read until the end of the current input line.
cin.ignore();
will skip until the next newline, so is very similar to while(cin.get() != '\n');
.
The whole code should check for end of file too, or it will hang (loop forever with failure) if no correct input is given and the input is "ended" (e.g. CTRL-Z or CTRL-D depending on platform).
Solution 2
// LINE 7:
cin.fail() detects whether the value entered fits the value defined in the variable.
// LINE 18:
cin leaves the newline character in the stream. Adding cin.ignore() to the next line clears/ignores the newline from the stream.
user2611244
Updated on June 14, 2022Comments
-
user2611244 almost 2 years
while (!correct) { cout << "Please enter an angle value => "; cin >> value; //request user to input a value if(cin.fail()) // LINE 7 { cin.clear(); // LINE 9 while(cin.get() != '\n'); // LINE 10 textcolor(WHITE); cout << "Please enter a valid value. "<< endl; correct = false; } else { cin.ignore(); // LINE 18 correct =true; } }
Hi, this is part of the code that I have written. The purpose of this code is to restrict users to input numbers like 10,10.00 etc, if they input values like (abc,!$@,etc...) the code will request users to reenter the values.
In order to perform this function( restrict user to input valid valus), I get some tips and guides through forums.
I think is my responsibility to learn and understand what these codes do... since this is the first time I use this code. can someone briefly explain to me what does the codes in line 7,9,10, and 18 do? Especially line 10. I got a brief idea on others line just line 10 I don't know what it did.
Thanks for your guides, I appreciate that!
-
user2611244 almost 11 yearsThanks for the details!
-
user2611244 almost 11 yearsThanks for the details!
-
user2611244 almost 11 yearsThanks for the details!