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

前端 未结 6 546
囚心锁ツ
囚心锁ツ 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.

提交回复
热议问题