I have the following for loop, I am prompting the user to enter a 4 digit pin and hit enter. Can someone explain to me what the while loop is really doing because I don\'t f
When you give input to the program, then you end it with the Enter key. This key is sent to your program as a newline.
What the loop does is to read and discard characters until it has read the newline. It flushes the input buffer.
If you don't do this, then the next main getchar
call would return the newline instead of the digit you expect.
The while loop is used to check when the user will press enter.Enter is considered as '\n'.
As mentioned by others, this loop discards unwanted characters from stdin
so that the next input function has a clean stream, and in particular it discards the \n
that follows the last character entered by the user. But, getchar()
returns EOF
in the event of a read error, so the loop should test for EOF
also, like this:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF)
continue; // discard unwanted characters
Also note that, if stdin
has been redirected, it is possible to reach EOF
without encountering a \n
. And, as @chqrlie pointed out in the comments, the user can signal an EOF
from the terminal by entering Ctrl-D
in Linux, or Ctrl-Z
in Windows. Hence the importance of testing for EOF
explicitly.
That line is a while, so at run-time it will repeat it until getchar() == '\n'. '\n' is a character that in ASCII means "enter" key. In this way you can test that the user will not press "enter" without had inserted a number.
**The function of this while loop is to clear the users' illegal input .When the input is '\n' ,the loop ends.
The next line is discarding the possible extra chars that the user may have inputted, and also the linefeed char that the user had to input.
So other scanf/getchar
methods further in the code are not polluted by this spurious input.