0

How does the following code works to clear only the failbit in the cin stream?

cin.clear(cin.rdstate() & ~cin.failbit);

I am highly confused, as I was under the impression that cin.rdstate() returns an object of type iostate. This is then somehow compared with a single bit (cin.failbit) to clear only said bit. How exactly do the & and ~ work to achieve this?

Holt
  • 36,600
  • 7
  • 92
  • 139
Nick.T
  • 13
  • 2
  • 2
    https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit – Matteo Italia Dec 25 '17 at 22:57
  • 1
    `iostate` is a type for which bitwise operations are allowed (which means it is either an integral type, or a type with defined operators that have "like integer" semantics). `cin.failbit` will have only the fail bit(s) set, `~cin.failbit` will have all bits EXCEPT the fail bit(s) set. The `&` then gives the result of clearing only the fail-related bits of `rdstate()`. – Peter Dec 25 '17 at 23:00
  • Just a hint. 'Bit' is note a variable type in C/C++. The closest to it would be `bool`. What you see there is not 'a single bit', but a number. Bitwise operators (e.g. &, ~) work on numbers. – ypnos Dec 25 '17 at 23:01
  • Possible duplicate of [How do you set, clear, and toggle a single bit?](https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit) – Passer By Dec 26 '17 at 02:16

0 Answers0