为什么C程序的打印0D而不是0? (EOF时发送,按Ctrl + D) [英] Why does C program print 0D instead of 0? (When EOF sent as Ctrl+D)

查看:341
本文介绍了为什么C程序的打印0D而不是0? (EOF时发送,按Ctrl + D)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OSX 10.6.8,GCC 4.2 86_64

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

preSS CTRL + D 发送EOF

0D

这应该只是0.为什么会追加D'这是什么意思?

It should be just 0. Why does it append D? What does it mean?

推荐答案

我已经看到了这一个 - 它搞糊涂了,太

I've seen this one - it confused me, too.

该终端呼应 ^ D ,然后 0 从程序的输出,覆盖插入符。

The terminal is echoing ^D and then the 0 is output from the program, overwriting the caret.

您可以通过改变程序中的打印格式,以证明这一点\\ n%d个\\ N

You can demonstrate this by changing the print format in your program to "\n%d\n".

在问'为什么?',我去探索。答案是在tty设置。对于我的终端,从的stty -a 的输出是:

When asked 'Why?', I went exploring. The answer is in the tty settings. For my terminal, the output from stty -a is:

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 在第二行的末尾 - 它是回声控制字符

Notice the echoctl at the end of the second line - it is for 'echo control characters'.

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

您无法看到它,但每个命令,我输入一个控制-D 在该行的末尾 ASD 字符,并创下返回后的第二个。提示在第二个例子删除第二呼应 ^ D

You can't see it, but for each cat command, I typed a Control-D at the end of the line of asd characters, and a second one after hitting return. The prompt erased the second echoed ^D in the second example.

所以,如果你不喜欢控制字符被回荡,关掉呼应:

So, if you don't like the control characters being echoed, turn the echoing off:

stty -echoctl

外壳还可以得到的方式;我尝试用<大骨节病>控制-R 和我的壳(庆典)决定进入

(reverse-i-search)`': aasadasdadadasdadadadadadsad

我已经输入的ASD字符喧宾夺主序列,然后键入<大骨节病>控制-R ,而这正是我在shell结束了。我打断;我不知道一个反向我搜索是什么,但我怀疑它是Emacs的杂交;这是不是我的预期。

I'd typed the unoriginal sequence of 'asd' characters and then typed Control-R, and this is where I ended up in the shell. I interrupted; I'm not sure what a reverse-i-search is, but I suspect it is Emacs-ish; it was not what I expected.

这篇关于为什么C程序的打印0D而不是0? (EOF时发送,按Ctrl + D)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆