Home c++ cin.ignore; cin.clear; cin.fail

cin.ignore; cin.clear; cin.fail

Author

Date

Category

found an example code using these functions, but I do not understand what they need and how they work

double getvalue ()
 {
While (True) // The cycle continues until the user enters the correct value
 {
  STD :: COUT & LT; & LT; "ENTER A DOUBLE VALUE:";
  Double A;
  STD :: CIN & GT; & GT; A.
  if (std :: cin.fail ()) // If the previous extraction turned out to be unsuccessful,
  {
    STD :: CIN.CLEAR (); // then return CIN to 'normal' mode
    STD :: CIN.IGNORE (32767, '\ n'); // and delete the value of the previous input from the input buffer
  }
  else // if everything is fine, then we return a
    RETURN A;
}

}


Answer 1, Authority 100%

Stream objects, such as Cin and Cout , as well as any other object, have a specific state. For them, the status is estimated to install certain bits, GoodBit (installed by default and has a zero value), Badbit, Failbit . If for some reason the flow “broke”, then the Badbit will be installed, and the program is accidentally completed. If there was an attempt to read the type, but it is impossible to read it from the buffer, then the status of failbook is set.

  1. std :: cin.fail () will mean: yes, installed failbook , so
    Any attempt to read further will be unsuccessful. std :: cin
    Wait for cleaning all set status bits.
  2. This is done by the STD :: CIN.CLEAR , the challenge of which leads to
    reset all the status bits, and this is Goodbit . Only after
    This can try to read something else. If we decide that in
    such cases (once there was no number there) you need to skip the string and
    try to read the number in the new line, then we give the team
    “ignore” (read, but leave in buffer) many characters while
    Do not meet the line translation symbol.
  3. std :: cin.ignore (32767, '\ n'); And there is this command (instead of 32767
    Maybe any big digit is such that exactly more than
    Number of characters to ‘\ n’)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions