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.
std :: cin.fail ()
will mean: yes, installedfailbook
, so
Any attempt to read further will be unsuccessful.std :: cin
Wait for cleaning all set status bits.- This is done by the
STD :: CIN.CLEAR
, the challenge of which leads to
reset all the status bits, and this isGoodbit
. 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. std :: cin.ignore (32767, '\ n');
And there is this command (instead of32767
Maybe any big digit is such that exactly more than
Number of characters to ‘\ n’)