getChar()在第二次称为第二次时保持返回eof值

发布于 2025-01-23 12:51:53 字数 727 浏览 3 评论 0 原文

我很难理解 getchar() eof 。 我试图运行此代码:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char c;
    int a = 0; //no. of characters
    while (1) {
        c = getchar();
        if (c == EOF) {
            // printf("%i",c); 
            break;
        }
        putchar(c);
        ++a;
    }
    printf("%i", a);
    int b;
    while ((b = getchar()) != EOF) {
        putchar(b);
    }
    printf("here"); // to check wether the code written after the loop is executed
}

我两次按CTRL-D终止了第一个循环,我发现了许多帖子,解释了其原因。但是,每当我尝试调用 getchar()函数后,第一个循环后,即使在第一个循环中的最后一个调用中,它已经通过了最后一个调用来返回 eof

代码编辑器-VSCODE

OS -MACOS

I have trouble understanding getchar() and EOF.
I was trying to run this code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char c;
    int a = 0; //no. of characters
    while (1) {
        c = getchar();
        if (c == EOF) {
            // printf("%i",c); 
            break;
        }
        putchar(c);
        ++a;
    }
    printf("%i", a);
    int b;
    while ((b = getchar()) != EOF) {
        putchar(b);
    }
    printf("here"); // to check wether the code written after the loop is executed
}

I terminated the first loop by pressing Ctrl-D twice, I found many posts explaining the reason for this. But whenever I try to call the getchar() function after the first loop it keeps returning EOF, even though that would have been already read by the last call in the first loop.

Code editor - VSCode

OS - macOS

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

贪恋 2025-01-30 12:51:53

您必须将 c 定义为 int ,以适应来自 getchar()的可能返回值的完整范围,即类型 unsigned char 和特殊负值 eof (通常定义为( - 1))。

在大多数Unix系统上,当 ctrl-d ctrl-d “> canonical 模式,终端缓冲的任何输入都将发送到该过程。就您而言,这会导致输入回声。如果没有此类输入待处理,则终端将零字节发送到该过程,该过程被OS解释为文件末尾。击打 ctrl-d 连续两次,或更精确地在读取请求开始时立即返回 eof ,而无需从终端请求更多用户输入。

You must define c as an int to accommodate for the full range of possible return values from getchar(), namely all values of type unsigned char and the special negative value EOF (usually defined as (-1)).

On most unix systems, when Ctrl-D is typed in the terminal in canonical mode, whatever input has been buffered by the terminal is sent to the process. In your case, it causes the input to be echoed. If there is no such input pending, the terminal sends zero bytes to the process, which is interpreted by the OS as the end of file. Hitting Ctrl-D twice in a row, or more precisely at the beginning of a read request, does not enter an EOF byte, it signals the end of file to the reading process, hence any further attempt at reading from the stream will return EOF immediately without requesting more user input from the terminal.

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