Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cin.clear(ios_base::failbit) vs cin.setstate(ios_base::failbit)

Tags:

c++

istream

For one of my assignments, I was told to use cin.clear(ios_base::failbit) to set the failbit. I wonder, what is the difference between cin.clear(ios_base::failbit) and cin.setstate(ios_base::failbit)? Is the latter not clearer? I am a bit surprised to see how the failbit is set with clear(). Why such a counter-intuitive way for using clear()?

like image 344
CaTx Avatar asked Oct 17 '25 23:10

CaTx


1 Answers

I am a bit surprised to see how the fail bit is set with clear(). Why such a counter-intuitive way for using clear()?

Well let's think about it.

 std::cin.setstate(ios_base::failbit);

This will set the fail bit if it isn't already set, but preserve any other stream error state for std::cin.

 std::cin.clear(ios_base::failbit);

This will clear all the stream error state from std::cin and then set only the fail bit.

like image 97
Justin Randall Avatar answered Oct 20 '25 11:10

Justin Randall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!