Someone told me to use this code to clear the input buffer..

while((ch=getchar())!='\n' && ch !=EOF);

But I fail to understand how it actually works.

For example, there are two newline characters in the buffer

This is my buffer

\n \n

Now getchar() grabs the first '\n', stores it in ch and compares ch with '\n' and EOF to see if the condition is true or not. Like this

(ch != '\n' && ch !=EOF)
This gives

(false && true) = false.

So the condition is false, the loop will terminate. What about the second '\n'? Its still in the buffer !!! So is this code for clearing only 1 newline character from the buffer?:idea:

>What about the second '\n'?
It doesn't exist. That loop is designed for line-oriented interactive input from stdin. Because a newline is expected to terminate the buffering mechanism for your shell, there will only ever be one newline, and that newline will mark the end of the buffer. As such, the loop isn't a complete solution, but it's close enough if you use it for the purpose it was designed.

OK so there can't be two newline characters in buffer. How about an EOF following the \n?

\n EOF

>As such, the loop isn't a complete solution

What is the possible complete solution?

>How about an EOF following the \n?
That won't happen either. When you press the Enter key, the buffered characters in the shell are sent to your program for processing. That means every character up to and including the newline represent a single input transaction. You can't add characters to the transaction after sending it in for processing, so the EOF signal would be a part of the next transaction, making it irrelevant to this transaction.

The two situations you've described won't happen in line-oriented interactive input, but they can happen if stdin is redirected to a file, which is why this isn't a complete solution. However, the "newline stuck in the input stream" problem doesn't seem to be as much of an issue when dealing with files. It's usually a matter of people not fully understanding how streams work and muxing up interactive input.

>What is the possible complete solution?
There isn't one. When more than one interpretation for a stream of characters exists, it's impossible to have a complete solution to any problem because for at least one interpretation, it won't even be a problem.