while(getchar()!='\\\<br/>'); [英] while (getchar () != &#39;\n&#39; );

查看:167
本文介绍了while(getchar()!='\\\<br/>');的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下for循环,我提示用户输入一个4位数的引脚,然后按回车。有人可以向我解释什么是while循环,因为我不完全理解它。

$ p $ //用户输入引脚
(i = 0; i< PIN_LENGTH; i ++)
{
printf(输入PIN的数字%d,i);
user_pin [i] = getchar();
while(getchar()!='\\\
'); //这行是干什么的?

$ / code>


解决方案

循环从 stdin 丢弃不需要的字符,以便下一个输入函数有一个干净的流,特别是丢弃 \ n 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆