while(getchar()!='\\\<br/>'); [英] while (getchar () != '\n' );
问题描述
$ p $
//用户输入引脚
(i = 0; i< PIN_LENGTH; i ++)
{
printf(输入PIN的数字%d,i);
user_pin [i] = getchar();
while(getchar()!='\\\
'); //这行是干什么的?
$ / code>
解决方案循环从 stdin
丢弃不需要的字符,以便下一个输入函数有一个干净的流,特别是丢弃 \ n $ c $跟随用户输入的最后一个字符。但是,如果发生读取错误, getchar()
返回 EOF
,所以循环应该测试 EOF
也是如此:
int ch; ((ch = getchar())!='\ n'&& ch!= EOF)
continue; //放弃不需要的字符
还要注意,如果 stdin
已被重定向,可以在不遇到 \\\
的情况下达到 EOF
。而@chqrlie在评论中指出,用户可以通过输入 Ctrl-D
来从终端发信号给 EOF
>在Linux中,或在Windows中 Ctrl-Z
。因此显式测试 EOF
的重要性。
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??
}
解决方案 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.
这篇关于while(getchar()!='\\\<br/>');的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!