【问题标题】:Why is getchar() in C printing characters?为什么 getchar() 在 C 中打印字符?
【发布时间】:2020-07-02 04:41:32
【问题描述】:
#include <stdio.h>

main()
{
    long nc;
    nc = 0;
    
    while(getchar() != EOF)
        ++nc;
    printf("%ld\n", nc);
}

当我运行这个程序并为 ex 'helloworld' 编写一个字符串并按 Ctrl + D 时。它会再次打印我的字符串 - 'helloworldhelloworld'。

然后我再次打印 Ctrl + D 并显示:

helloworldhelloworld^D
Count: 10

为什么 Ctrl + D 不能立即打印计数? 在 Mac OS 上使用 Visual Studio Code。

编辑:我发布了错误的代码。真的很抱歉。

#include <stdio.h>

main()
{
    int c;
    int counter_a = 0;
    
    c = getchar();
    while(c != EOF)
    {
        putchar(c);
        c = getchar();
        counter_a = counter_a + 1;
    }

    printf("\nCount: \t%d\n", counter_a);
}

这是我正在运行的代码。所以我的问题解决了。

【问题讨论】:

  • 这个程序不应该打印任何字符串。删除可执行文件,然后重新编译并确保您正在运行正确的程序。
  • 请务必标记您正在使用的编程语言。像我这样的人会忽略不相关的标签,因此我们可以帮助人们处理我们知道的事情。 ;-)
  • 它工作正常,Ctrl-d 将停止接收进一步的输入流。请参考 C 上的FAQ

标签: c getchar


【解决方案1】:

Control D 不是 EOF 字符。相反,它强制控制台输入缓冲区逻辑使迄今为止输入的任何字符都可用于 stdio 库。如果 stdio 库发出的读取请求产生任何数据,则该库将期望之后会有更多数据。但是,如果读取请求没有产生任何数据,stdio 库将假定这是因为它到达了文件的末尾。

我不确定为什么要回显字符串,但控制台输入缓冲逻辑有时会在输入字符时回显字符,并且在某些情况下会回显部分完成的行。

在我看来,这是一个非常糟糕的方案,但这就是 Unix 的工作方式。

【讨论】:

【解决方案2】:

当您在 Posix 命令行中向程序输入输入并想要结束输入时,请在其他空行上输入 Ctrl-D

您的终端位于cooked mode,本质上是每个命令的行编辑器。在使用回车键“输入”该行之前,您的程序不会接收输入。如果您正在编辑的行不为空,Ctrl-D 将导致它被发送到终端输入的目的地(您的程序),而没有伴随回车键的换行符。

对于 行缓冲区,Ctrl-D 是操作员通知 shell 将文件结束条件应用于连接到键盘的输入流的方式。

cat 为例,该程序在此调用中将其输入流写入其输出流,与问题的程序不同。

$ cat
Usually, I can edit a line - using backspace to edit the input before I enter it.  Now I will press enter
Usually, I can edit a line - using backspace to edit the input before I enter it.  Now I will press enter
Mid-line, I can press Ctrl-D to send the line.  I'll press it now: Mid-line, I can press Ctrl-D to send the line.  I'll press it now:

I pressed enter after that was output, rendering both the newline I typed, echoed to the terminal, and the newline cat received.
I pressed enter after that was output, rendering both the newline I typed, echoed to the terminal, and the newline cat received.
But, at an empty line buffer, Ctrl-D ends input altoghether.  I'll press return, and then Ctrl-D.
But, at an empty line buffer, Ctrl-D ends input altoghether.  I'll press return, and then Ctrl-D.

当我按下 enter/return 时,我一直在编辑的行被发送到终端的目的地 (cat) - 包括换行符。当我在中线按下 Ctrl-D 时,我一直在编辑的行被发送到目的地 没有 换行符。空行上的 Ctrl-D(您可能已经键入,然后删除,但现在该行是空的)告诉输入阅读器没有更多数据,就像当您的位置已经在末尾时从文件中读取时一样。

【讨论】:

    猜你喜欢
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    相关资源
    最近更新 更多