2

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

#include <iostream>

int main()
{
 while(true)
 {
  bool f;
  if (std::cin >> f)
   std::cout << f << '\n';
  else
  {
   std::cout << "i/o error\n";
   std::cin.clear();
  }
 }
 return 0;
}

Here is the output I get:

g++ -Wall -ansi -pedantic -o boolio boolio.cpp
./boolio
0
0
1
1
2
i/o error
-
i/o error
t
i/o error
i/o error
i/o error
... (infinite loop)

I wonder why I get an infinite loop when I enter 't', and how to prevent it.

Thanks.

Rémi
  • 3,705
  • 1
  • 28
  • 39

3 Answers3

3

Add this line after clearing cin:

std::cin.ignore();

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

mfontanini
  • 21,410
  • 4
  • 65
  • 73
  • That works, thanks. But I still don't understand why '-' or '2' don't require it, while 't' requires it. – Rémi Feb 10 '11 at 17:26
  • 2
    Because a bool is read as a long (unless you use boolalpha), which is then checked for being 0 or 1. Long history, I guess. – Bo Persson Feb 10 '11 at 19:13
2

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.

Thiem Nguyen
  • 6,345
  • 7
  • 30
  • 50
tstanisl
  • 21
  • 1
1

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)

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Karthick K
  • 55
  • 1
  • 6