Seungbeom Kim said:
But how large should the buffer be?
The larger it is, the more memory you waste (though it may not matter
that much here). The smaller, the more likely it is that you'll get
the original problem of multiple prompts between newlines, unless you
carefully write a loop to consume the remnants of the line.
It is easy to write a "sloppy" version which will most likely work for
this type of non-critical interactive programs, but it is not trivial
to write a perfectly correct version.
It /is/ harder than it looks at first.
If line-oriented input is to be used (and that fits in better if the rest of
the application is command-line based), then the steps are these:
* Read an entire line into a buffer.
* Detect and return the two Y/y or N/n possibilities in the buffer (and
possibly also Yes and No), and reject every other kind of input
* Repeat until Y or N is seen.
This seems simple enough, although if you're writing this from scratch, you
will quickly see you might be doing this a lot and should be building
functions for more general use. For just starting however, throwing together
anything that will work will do.
However, C likes to throw some obstacles in the way. For example, in this
newsgroup, it is impossible to talk about any code to do with line input
(especially from a console or terminal), without it having to deal sensibly
with:
* Having input redirected from a file
* Files potentially containing lines too long for any reasonable-sized
buffer
* A possible huge, multi-GByte file
* Dealing a binary file that doesn't contain any line or text data
* All of the above.
(I've looked at how easy it might be to code the OP's task in a couple of
other languages I use. In a dynamic language, it was easy. In another, more
C-like one, it was still straightforward (but that language had line input
built-in; example is here:
http://pastebin.com/CAv1P9yn)
So they both work fine when used as expected (interactive console). But
neither of them cope fully when given some completely random binary file.
But it doesn't matter! The program is being used incorrectly so it is
expected to go wrong.
The main issue is that when reaching an EOF, it will keep reading empty
lines. I might make a concession for that and return 'N' on an empty line,
or apply some limit to the number of empty (or error) lines tolerated (not
shown in my link).
Another approach is to detect such attempts to read past EOF internally and
raise an error (or simply close the file and switch to interactive mode).
But I don't think explicit EOF-checking is appropriate in user-level code
designed for interactive input.)