Windows命令提示符中的EOF不会终止输入流 [英] EOF in Windows command prompt doesn't terminate input stream

查看:138
本文介绍了Windows命令提示符中的EOF不会终止输入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

#include <stdio.h>
#define NEWLINE '\n'
#define SPACE ' '

int main(void)
{
    int ch;
    int count = 0;

    while((ch = getchar()) != EOF)
    {
        if(ch != NEWLINE  && ch != SPACE)
            count++;
    }
    printf("There are %d characters input\n" , count);

    return 0;
}

问题:


  1. 一切正常,它将忽略空格和换行符,并将输入的字符数输出到屏幕上(在此程序中,我只使用逗号,感叹号,数字或任何可打印的特殊符号字符,例如&字符),当我点击EOF模拟时,它是 ^ z

但是当我在程序中输入这一行时出了点问题。例如,我输入以下内容: abcdefg ^ z ,这意味着我在 ^ z 。程序将继续要求输入,而不是终止程序并打印出总字符。

But there's something wrong when I input this line to the program. For example I input this: abcdefg^z, which means I input some character before and on the same line as ^z. Instead of terminating the program and print out total characters, the program would continue to ask for input.

仅当我指定<$时,EOF终止字符输入才有效c $ c> ^ z 或执行以下操作: ^ zabvcjdjsjsj 。为什么会发生这种情况?

The EOF terminating character input only works when I specify ^z on a single line or by doing this: ^zabvcjdjsjsj. Why is this happening?


推荐答案

几乎在每个终端驱动程序中都是如此。使用Linux,您会得到相同的行为。

This is true in almost every terminal driver. You'll get the same behavior using Linux.

您的程序直到 \n ^ z才真正执行循环您已在行尾输入。终端驱动程序正在缓冲输入,直到发生输入才将其发送给您的进程。

Your program isn't actually executing the loop until \n or ^z has been entered by you at the end of a line. The terminal driver is buffering the input and it hasn't been sent to your process until that occurs.

在一行的末尾,按 ^ z (或在Linux上为 ^ d )不会 导致终端驱动程序发送EOF。它只会使它刷新缓冲区到您的进程(没有 \n )。

At the end of a line, hitting ^z (or ^d on Linux) does not cause the terminal driver to send EOF. It only makes it flush the buffer to your process (with no \n).

命中 ^ z (或Linux上的 ^ d )在行首被终端解释为我想发信号给EOF。

Hitting ^z (or ^d on Linux) at the start of a line is interpreted by the terminal as "I want to signal EOF".

如果在循环中添加以下内容,则可以观察到此行为:

You can observe this behavior if you add the following inside your loop:

printf("%d\n",ch);

运行程序:

$ ./test
abc                      <- type "abc" and hit "enter"
97
98
99
10
abc97                    <- type "abc" and hit "^z"
98
99

要更好地理解这一点,您必须意识到EOF不是字符。 ^ z 是用于终端本身的用户命令 。因为终端负责接收用户输入并将其传递给流程,所以这变得很棘手,从而造成混乱。

To better understand this, you have to realize that EOF is not a character. ^z is a user command for the terminal itself. Because the terminal is responsible for taking user input and passing it to processes, this gets tricky and thus the confusion.

一种查看方式是点击 ^ v 然后点击 ^ z 作为程序的输入。

A way to see this is by hitting ^v then hitting ^z as input to your program.

^ v 是另一个告诉终端的终端命令, 嘿,我要输入的下一个内容-不要将其解释为终端命令;而是将其传递给流程的输入。

^v is another terminal command that tells the terminal, "Hey, the next thing I type - don't interpret that as a terminal command; pass it to the process' input instead".

这篇关于Windows命令提示符中的EOF不会终止输入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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