getchar() 和 putchar()

发布于 2024-08-20 05:22:20 字数 246 浏览 6 评论 0原文

在例子中:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不即不离 2024-08-27 05:22:20

这称为缓冲,由操作系统完成。通常它会进行行缓冲,只是将您放入其中的每个字符保存在内存中,然后在遇到换行符时将其全部写入文件。这可以节省资源,因为文件操作比其他操作花费更多的时间。因此,它不是对每个字符进行输出,而是等待一堆字符收集到缓冲区中,然后一次性将它们全部写出。

这只是操作系统所做的一个巧妙的操作,程序员无需担心。只需将你的角色一一扔给它,然后让操作系统以自己的方式处理其余的事情。

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.

合久必婚 2024-08-27 05:22:20

[这不是答案,但你不能在评论中添加代码]

我认为你的意思是这样的:

#include <stdio.h>

main()
{
    long nc;
    nc = 0;
    char c;
    while ((c = getchar()) != EOF)
    {
       putchar(c); /* prints one char */
        ++nc;
    }
    printf("%ld\n", nc); /* prints the number of characters read */
}

[This isn't an answer, but you can't put code in the comments]

I think you meant something like this:

#include <stdio.h>

main()
{
    long nc;
    nc = 0;
    char c;
    while ((c = getchar()) != EOF)
    {
       putchar(c); /* prints one char */
        ++nc;
    }
    printf("%ld\n", nc); /* prints the number of characters read */
}
装迷糊 2024-08-27 05:22:20

没有位置,此代码仅清空输入并写入刷新前剩余的字符数。

这是为了确保输入文件(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)

小耗子 2024-08-27 05:22:20

putchar 当输入时将字符放入缓冲区,然后它将把行字输出到屏幕上。

putchar put the char into the buffer when it comes an enter ,then it will bring the line word output to the screen.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文