getchar() != EOF
Asked Answered
F

1

5

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', '\n', '^D'} then I get the following response printed to screen: hello, after \n 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 \n. 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.

Futurism answered 28/11, 2014 at 7:29 Comment(0)
C
18

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.

Coe answered 28/11, 2014 at 7:41 Comment(2)
note that this is a property of the operating system input stream, not of the C program.Moonfish
Thank you, Marian and Matt McNabb. I thought that the input buffer is only flushed by typing newline character. I was not aware of a similar behavior with ^D as well.Futurism

© 2022 - 2024 — McMap. All rights reserved.