ctrl-d 没有停止 while(getchar()!=EOF) 循环 [英] ctrl-d didn't stop the while(getchar()!=EOF) loop
问题描述
这是我的代码.我用终端在 ubuntu 中运行它.当我在终端中输入 (a CtrlD) 时,程序并没有停止,而是继续等待我的输入.
Here is my code. I run it in ubuntu with terminal. when I type (a CtrlD) in terminal, the program didn't stop but continued to wait for my input.
CtrlD在unix中不是等于EOF吗?
Isn't CtrlD equal to EOF in unix?
谢谢.
#include<stdio.h>
main() {
int d;
while(d=getchar()!=EOF) {
printf(""getchar()!=EOF" result is %d
", d);
printf("EOF:%d
", EOF);
}
printf(""getchar()!=EOF" result is %d
", d);
}
推荐答案
EOF 不是字符.EOF
是 getchar()
到达输入末尾或遇到某种错误时返回的宏.^D
不是EOF 字符".在 linux 下,当你在一行上按 ^D 时发生的事情是它关闭了流,并且 getchar()
调用到达输入的末尾并返回 EOF
宏.如果您在一行中间的某处键入 ^D
,则流不会关闭,因此 getchar()
返回它读取的值并且您的循环不会退出.
EOF is not a character. The EOF
is a macro that getchar()
returns when it reaches the end of input or encounters some kind of error. The ^D
is not "an EOF character". What's happening under linux when you hit ^D on a line by itself is that it closes the stream, and the getchar()
call reaches the end of input and returns the EOF
macro. If you type ^D
somewhere in the middle of a line, the stream isn't closed, so getchar()
returns values that it read and your loop doesn't exit.
请参阅 C 常见问题的 stdio 部分 以获得更好的描述.
See the stdio section of the C faq for a better description.
另外:
在现代系统上,它不反映存储在文件中的任何实际文件结束字符;这是没有更多可用字符的信号.
On modern systems, it does not reflect any actual end-of-file character stored in a file; it is a signal that no more characters are available.
这篇关于ctrl-d 没有停止 while(getchar()!=EOF) 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!