0

What is the use of cin.fail?

15th Dec 2016, 6:53 AM
Charlon Jios
Charlon Jios - avatar
3 Answers
+ 1
Hello, cin.fail() detects whether the value entered fits the value defined in the variable. But if cin.fail() is true, it means that a) the entered value does not fit the variable b) the varialbe will not be affected c) the instream is still broken d) the entered value is still in the buffer and will be used for the next "cin >> variable"statement. Hence you have to do the following: a) repair the instream via cin.clear(); b) clear the buffer with cin.ignore(std::numeric_limits<int>::max(),'\n'); In your exampe, you have the result that, after entering the wrong value, your stream is broken. But you do not repair the stream and you do not clear the buffer. So, no matter how often the loop will be made, "cin >> number" will always retrieve the FIRST value you have entered after starting the programm. And thus, it will always return a cin.fail() and your loop can not be left by any value you will enter afterwards.
15th Dec 2016, 7:01 AM
TechBeat
TechBeat - avatar
+ 1
nice..tq bro..God bless u bro..â˜ș
15th Dec 2016, 8:40 AM
Charlon Jios
Charlon Jios - avatar
0
Gud luck
15th Dec 2016, 3:57 PM
TechBeat
TechBeat - avatar