while (getchar() != ' ' ); [英] while (getchar () != ' ' );
问题描述
我有以下 for 循环,我提示用户输入一个 4 位数的 pin 并按回车键.有人可以向我解释 while 循环到底在做什么,因为我不完全理解它.
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() != '
'); //what is this line doing??
}
推荐答案
正如其他人提到的,这个循环从 stdin
中丢弃不需要的字符,以便下一个输入函数有一个干净的流,特别是它丢弃用户输入的最后一个字符之后的
.但是,getchar()
在读取错误的情况下返回 EOF
,因此循环也应测试 EOF
,如下所示:>
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
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()) != '
' && ch != EOF)
continue; // discard unwanted characters
另请注意,如果 stdin
已被重定向,则可以到达 EOF
而不会遇到
.而且,正如@chqrlie 在评论中指出的那样,用户可以通过在 Linux 中输入 Ctrl-D
或 Ctrl-Z<从终端发出
EOF
信号/code> 在 Windows 中.因此,明确测试 EOF
的重要性.
Also note that, if stdin
has been redirected, it is possible to reach EOF
without encountering a
. 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.
这篇关于while (getchar() != ' ' );的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!