while (getchar () != '\n' );

前端 未结 6 506
囚心锁ツ
囚心锁ツ 2021-01-03 17:08

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

相关标签:
6条回答
  • 2021-01-03 18:01

    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.

    0 讨论(0)
  • 2021-01-03 18:04

    The while loop is used to check when the user will press enter.Enter is considered as '\n'.

    0 讨论(0)
  • 2021-01-03 18:05

    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.

    0 讨论(0)
  • 2021-01-03 18:11

    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.

    0 讨论(0)
  • 2021-01-03 18:13

    **The function of this while loop is to clear the users' illegal input .When the input is '\n' ,the loop ends.

    0 讨论(0)
  • 2021-01-03 18:14

    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.

    0 讨论(0)
提交回复
热议问题