2

I wanted to ignore all characters in cin to flush cin in this answer: How to get rid of bad input one word at a time instead of one line at a time?

But I found that the program seemed to hang awaiting input if I wrote:

cin.ignore(std::numeric_limits<std::streamsize>::max());

It propperly flushed cin if I used the '\n' delimiter:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

My question is, why can't I just ignore till EOF? Why do I have to provide the delimiter?

kaya3
  • 47,440
  • 4
  • 68
  • 97
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • You *can* ignore till EOF. You *did* ignore till EOF. You just didn't realize what that actually means. ;-) – DevSolar Feb 20 '15 at 16:14
  • Did you make it reach the end of `cin`, either by redirecting from a file or other finite source, or hitting CTRL-D or whatever it is on your platform? Otherwise, it will wait for input to ignore forever. – Mike Seymour Feb 20 '15 at 16:32
  • So your desire is to discard all characters that have been currently entered, then start reading normally? That's a good question. – Mark Ransom Feb 20 '15 at 18:17
  • @MarkRansom Right. It seems the answer was more clear than I thought it was, I just didn't understand `ignore`. – Jonathan Mee Feb 20 '15 at 18:37

1 Answers1

5

The ignore function name is a little bit misleading. What it actually does it read and discard input until the terminator is found. And that's a blocking read.

In your case, whatever input stream you are using with cin (by default it is stdin) never delivers an end-of-file condition, so ignore's read/discard loop blocks forever.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Unless a pipeline is involved - than the writing end is emitting an EOF when closing. Another exemption is a user input in a terminal supporting EOF (Linux: ctrl-D) –  Feb 20 '15 at 16:44
  • On Windows you can mark EOF on the console with Ctrl-Z+Enter, and on *nix you do it with Ctrl-D. So it's not impossible to break out, just unlikely if you don't know the trick. – Mark Ransom Feb 20 '15 at 18:15
  • @Dieter, Mark: Right, I didn't say that the input stream is incapable of delivering an EOF, just that in his case it is not doing so. – Ben Voigt Feb 20 '15 at 19:14