Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

c - getchar() != EOF

I am running the following program from the C Programming Language book:

#include <stdio.h>
main()
{
  int c;
  while((c=getchar()) != EOF)
    putchar(); 
}

Or

#include<stdio.h>
int main(){
   int c = getchar();
   while(c != EOF){
      putchar(c);
      c = getchar();
   }
}

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', ' ', '^D'} then I get the following response printed to screen: hello, after is input, and the program quits once ^D in entered.

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 . I don't understand why the program doesn't quit no matter when I enter ^D. Any thoughts?

I am running on a UNIX system.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...