仅使用CTRL-D一次后,如何使字计数程序(来自K& R)终止? [英] How can I make the word count program (from K&R) terminate after just one application of CTRL-D?

查看:67
本文介绍了仅使用CTRL-D一次后,如何使字计数程序(来自K& R)终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习使用C&在Unix中,通过在Vim中编写一些C程序并对其进行编译.

I'm practicing using C & Unix by writing up some of the C programs in Vim and compiling them.

当读取的字符为EOF(CTRL-D)时,字计数程序应该结束.但是,当我运行它时,第一次按下CTRL-D只会使其在终端上打印"^ D"(减去引号).第二次按下时,"^ D"消失,它正常终止.

The word count program is supposed to end when the character read is EOF (CTRL-D). However, when I run it, the first CTRL-D pressed just makes it print "^D" (minus the quotes) on the terminal. The second time it's pressed, the "^D" goes away and it terminates normally.

如何更改此设置,使其仅在一个CTRL-D之后终止?我注意到,如果我刚刚创建了换行符,那么只需按一次CTRL-D就可以了.但是我真的不明白为什么那样会起作用,而不是一般情况下.

How can I change this so that it terminates after only one CTRL-D? I notice that if I've just made a newline character, then pressing CTRL-D once does the trick. But I don't really understand why it works then and not in the general case.

对于那些没有这本书的人来说,程序就是这样的.

Here's what the program looks like for those of you who don't have the book.

#include <stdio.h>

#define IN   1   /* Inside a word */
#define OUT  0   /* Outside a word */

int main()
{
    int c, nl, nw, nc, state;
    state = OUT;
    nl = nw = nc = 0;
    while ((c = getchar()) != EOF) {
        ++nc;
        if (c == '\n') {
            ++nl;
            --nc;
        }
        if (c == ' ' || c == '\n' || c == '\t')
            state = OUT;
        else if (state == OUT) {
            state = IN;
            nw++;
        }
    }
    printf("%d %d %d\n", nl, nw, nc);
    return 0;
}

推荐答案

如果在行的开头键入 Control-D ,一次就足够了.如果您在键入任何内容后键入Control-D,则需要键入两次.

If you type Control-D at the start of the line, once should be enough. If you type Control-D after you've typed anything, then you need to type it twice.

这是因为 Control-D 告诉终端驱动程序将所有可用字符发送到任何等待的进程.当它在一行的开头时,没有可用的字符,因此等待 read()的进程将返回零个字符,这就是EOF的含义(没有可读取的字符).当它是一行的一部分时,第一个 Control-D 将字符发送到程序,该程序读取它们;第二个表示不再有字符,因此再次表示EOF.

That's because the Control-D tells the terminal driver to send all available characters to any waiting process. When it is at the start of a line, there are no available characters, so a process waiting on a read() gets zero characters returned, which is the meaning of EOF (no characters available for reading). When it is part way through a line, the first Control-D sends the characters to the program, which reads them; the second indicates no more characters and hence EOF once more.

这篇关于仅使用CTRL-D一次后,如何使字计数程序(来自K&amp; R)终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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