对“while(getchar() != '\n')”感到困惑
我知道 getchar() 只是一个函数,获取用户输入的行的第一个字符,然后获取下一个字符,依此类推 如果我们在一行中输入getchar()
,那么在代码结束时,这是为了让程序等待用户输入任何内容,并且在显示信息时不关闭控制台。
为什么我们使用这行代码?
while(getchar()!='\n');
我知道它会读取该行的所有字符,直到找到行尾然后循环中断..正确的 。?但是,为什么这有用呢?如果我们不写这行代码怎么办?
while((ch=fgetc(stream))!=EOF)
{
putchar(ch);
cha++;
if(ch=='\n')
{
lines++;
printf("Line %i is detected\n\n",lines);
if(lines==NEW_LINE)
{
lines=0;
while (getchar!='\n'); **//Here is my question**
}
}
}
I knew that getchar(
) is just a function gets the first character of the line the user entered then the next and so on
And if we typed getchar()
in a line, at the finishing of the code,it's for let the program wait for user to type any thing and for not closing the console when displaying the info.
why we use this line of code ?
while(getchar()!='\n');
I knew that it reads all characters of the line until the end of line is found then the loop breaks .. right .? But, why this is useful ? What if we don't write this line of code ?
while((ch=fgetc(stream))!=EOF)
{
putchar(ch);
cha++;
if(ch=='\n')
{
lines++;
printf("Line %i is detected\n\n",lines);
if(lines==NEW_LINE)
{
lines=0;
while (getchar!='\n'); **//Here is my question**
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来这段代码正在对输出进行分页。
它从流中一次读取一个字符,并使用 putchar 将其输出到 stdout。然后,如果该字符是换行符,则会增加行数。如果该计数达到某个定义的常量
STOP_LINE
,则计数将重置并等待用户按 Return 键。然后循环继续。
It looks like this code is paginating output.
It reads a character at a time from the stream and uses
putchar
to output it tostdout
. Then, if that character was a newline, it increments a count of lines. If that count has hit some defined constantSTOP_LINE
then the count is reset andwaits for the user to press Return. The loop then continues.
读取该行的所有字符,直到找到行尾。
然而,会有更有效的方法来做到这一点(例如使用缓冲流,或者如果可能的话读取更大的块)
Reads all characters of the line until the end of line is found.
There would be more efficient ways to do this, however (like using a buffered stream, or reading larger chunks if possible)