std::cin.clear() fails to restore input stream in a good state

前端 未结 3 740
心在旅途
心在旅途 2021-01-22 12:04

In order to test bool i/o, I tried to run this short program:

#include 

int main()
{
 while(true)
 {
  bool f;
  if (std::cin >> f)
   std         


        
相关标签:
3条回答
  • 2021-01-22 12:16

    Add this line after clearing cin:

    std::cin.ignore();
    

    This way, the stream ignores whatever is left on its buffer.

    0 讨论(0)
  • 2021-01-22 12:20

    if (std::cin >> f) expects either a 0 or 1. And treats all other values as an I/0 error. Even if you enter '-' or 2, std::cin.ignore() is still needed.

    If you want the program to enter only the values true or false, use the following statement instead of (std::cin >> f)

    (std::cin >> boolalpha >> f)

    0 讨论(0)
  • 2021-01-22 12:35

    Try to use following combo:

    cin.ignore(INT_MAX, '\n'); // ignore all characters in the current line
    
    cin.clear(); // restore 'good' flag
    

    Using only cin.ignore() will discard only one character in the buffer.

    0 讨论(0)
提交回复
热议问题