getchar() 和 putchar()
在例子中:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
我不太明白。 putchar() 会把字符放出来,但是为什么在 EOF 之后它就把所有字符都放出来了,它在哪里记住所有这些字符呢?谢谢。
in the example:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
I don't quite understand it. putchar() would put the character out, but why is it that after EOF it puts all the characters out, and where is it remembering all these characters? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这称为缓冲,由操作系统完成。通常它会进行行缓冲,只是将您放入其中的每个字符保存在内存中,然后在遇到换行符时将其全部写入文件。这可以节省资源,因为文件操作比其他操作花费更多的时间。因此,它不是对每个字符进行输出,而是等待一堆字符收集到缓冲区中,然后一次性将它们全部写出。
这只是操作系统所做的一个巧妙的操作,程序员无需担心。只需将你的角色一一扔给它,然后让操作系统以自己的方式处理其余的事情。
It's called buffering and it's done by the operating system. Usually it does line buffering where it just saves every character you put to it in memory, and then writes it all to the file when it encounters a line break. This saves on resources because file operations take much more time than other operations. So instead of doing output with every single character, it waits for a bunch of characters to collect in the buffer and writes them out all in one go.
It's just a clever maneuver done by the OS that you, the programmer, don't need to worry about. Just throw your characters at it one by one and let the OS handle the rest in its own way.
[这不是答案,但你不能在评论中添加代码]
我认为你的意思是这样的:
[This isn't an answer, but you can't put code in the comments]
I think you meant something like this:
没有位置,此代码仅清空输入并写入刷新前剩余的字符数。
这是为了确保输入文件(stdin)中没有剩余字符
No where, this code only empty the input and write how many caracters where left before the flush.
This is to be sure that the is no caracters remaining in the input file (stdin)
putchar 当输入时将字符放入缓冲区,然后它将把行字输出到屏幕上。
putchar put the char into the buffer when it comes an enter ,then it will bring the line word output to the screen.