的getchar()!= EOF [英] getchar() != EOF
问题描述
我是从C语言程序设计书上运行下面的程序:
I am running the following program from the C Programming Language book:
#include <stdio.h>
main()
{
int c;
while((c=getchar()) != EOF)
putchar();
}
当我运行这个程序,我得到一个无法解释的行为。如果从按以下顺序在命令行我输入的字符: {'H','E','L','L','O','\\ n','^ D'}
然后我得到以下响应打印到屏幕上:你好
,在 \\ n
输入,程序退出一旦 ^ D
中输入。
When I run this program, I get an unexplained behavior. If I input characters from the command line in the following sequence: {'h', 'e', 'l', 'l', 'o', '\n', '^D'}
then I get the following response printed to screen: hello
, after \n
is input, and the program quits once ^D
in entered.
然而,当我更改顺序如下: {'H','E','L','L','O','^ D'}
然后我得到打印到屏幕以下响应:你好
,但程序不会退出。难道不应该退出,一旦我进入 ^ D
?我必须输入 ^ D
第二次为程序退出。或者我已经进入 ^ D
后以下 \\ n
程序只退出。我不明白为什么当我进入 ^ D
程序不会退出不管。有什么想法?
However, when I change the sequence as follows: {'h', 'e', 'l', 'l', 'o', '^D'}
then I get the following response printed to screen: hello
, but the program does not quit. Shouldn't it quit once I enter ^D
? I have to enter ^D
a second time for the program to quit. OR the program only quits after I have entered ^D
following \n
. I don't understand why the program doesn't quit no matter when I enter ^D
. Any thoughts?
我在UNIX系统上运行。
I am running on a UNIX system.
推荐答案
当你输入^ D输入缓冲区清空,您键入到现在为止被发送到你的程序的一切(('传递结束),而不实际发送^ D字符)。它类似于输入换行符,然而,在此情况下,换行字符本身被发送了。程序考虑其输入时,它读取零字符关闭。出现这种情况,当你键入新行后跟^ D或两个连续的^ D。
When you type ^D ('end-of-transmission') the input buffer is flushed and everything you typed until now is sent to your program (without actually sending ^D character). It is similar to typing newline character, however, in this case the newline character itself is sent too. A program considers its input as closed when it reads zero characters. This happens when you type newline followed by ^D or two consecutive ^D.
这篇关于的getchar()!= EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!