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

喜你入骨 提交于 2019-12-19 05:11:10

问题


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 fully understand it.

//user input for pin
for(i = 0; i < PIN_LENGTH; i++)
{
    printf("Enter digit %d of your PIN: ", i);
    user_pin[i] = getchar();
    while (getchar() != '\n'); //what is this line doing??
}

回答1:


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.




回答2:


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.




回答3:


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.




回答4:


**The function of this while loop is to clear the users' illegal input such as 'a','.' and when it gets '\n' the loop ends.




回答5:


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




回答6:


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.



来源:https://stackoverflow.com/questions/40554617/while-getchar-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!