【问题标题】:Why does C program print 0D instead of 0? (When EOF sent as Ctrl+D) [duplicate]为什么C程序打印0D而不是0? (当 EOF 作为 Ctrl+D 发送时)[重复]
【发布时间】:2011-11-29 05:19:20
【问题描述】:

OSX 10.6.8、GCC 4.2 86_64

#include <stdio.h>

/* count lines in input */
main()
{
    int c, nl;

    nl = 0;
    while ((c = getchar()) != EOF)
        if (c == '\n')
            ++nl;
    printf("%d\n", nl);
}

运行

./a.out

ctrl+d发送EOF

0D

它应该只是0。为什么要附加D?什么意思?

【问题讨论】:

  • 如果您按 ctrl+D,那么听起来 D 来自终端...例如它与 printf (或代码?)无关。如果您尝试使用moreless 会发生什么?如果将输入通过管道输入到程序中会怎样?
  • 每次您将带有 CTR D 的 EOF 发送到任何程序或仅发送到此测试时,都会发生这种情况吗?我认为除了0 之外的D 只是来自上面的组合键。
  • 我在 linux 机器上运行时得到 0
  • @pst 不,D 不是来自那个 - ctrl+D 是发送 EOF 的快捷方式

标签: c macos


【解决方案1】:

我见过这个 - 它也让我感到困惑。

终端正在回显^D,然后程序输出0,覆盖插入符号。

您可以通过将程序中的打印格式更改为"\n%d\n" 来证明这一点。


当被问到“为什么?”时,我开始探索。答案在 tty 设置中。对于我的终端,stty -a 的输出是:

speed 9600 baud; 65 rows; 120 columns;
lflags: icanon isig iexten echo echoe -echok echoke -echonl echoctl
    -echoprt -altwerase -noflsh -tostop -flusho pendin -nokerninfo
    -extproc
iflags: -istrip icrnl -inlcr -igncr ixon -ixoff ixany imaxbel iutf8
    -ignbrk brkint -inpck -ignpar -parmrk
oflags: opost onlcr -oxtabs -onocr -onlret
cflags: cread cs8 -parenb -parodd hupcl -clocal -cstopb -crtscts -dsrflow
    -dtrflow -mdmbuf
cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = <undef>;
    eol2 = <undef>; erase = ^?; intr = ^C; kill = ^X; lnext = ^V;
    min = 1; quit = ^\; reprint = ^R; start = ^Q; status = ^T;
    stop = ^S; susp = ^Z; time = 0; werase = ^W;

注意第二行末尾的echoctl - 它用于“回显控制字符”。

$ stty -echoctl
$ cat > /dev/null
asdsadasd
$ stty echoctl
$ cat > /dev/null
asasada^D
$

你看不到它,但是对于每个cat 命令,我在asd 字符行的末尾键入了一个 Control-D,然后在按回车后键入了第二个.提示删除了第二个示例中回显的第二个 ^D

所以,如果您不喜欢回显控制字符,请关闭回显:

stty -echoctl

shell 也有碍事;我尝试了 Control-R 并且我的 shell (bash) 决定进入

(reverse-i-search)`': aasadasdadadasdadadadadadsad

我输入了非原始的 'asd' 字符序列,然后输入了 Control-R,这就是我最终进入 shell 的地方。我打断了;我不确定什么是反向搜索,但我怀疑它是 Emacs-ish;这不是我所期望的。

【讨论】:

  • 哇,那是正确的!但为什么它只发生在这种特殊情况下?还是一直都在发生?为什么会回显 ^D?
  • 非常感谢您进行所有这些研究!看到实现非常有趣。
【解决方案2】:

在 Mac OSX 上运行 Xcode 得到以下输出:

第一行
二线
现在我要在返回后按控制 D。
3

【讨论】:

  • 好吧,Xcode 不是 bash,所以它可能不会像 Jonathan 解释的那样输出 ^D。
  • 这可能是您的 tty 设置:查看stty -a 输出为[-]echoctl;如果你有-echoctl,你将看不到^D;如果你有echoctl,你会的。对我来说,这是标记为“lflags:”的行的结尾,stty -a 输出的第 2 行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多