Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getchar() != EOF

Tags:

c

getchar

putchar

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.

like image 583
Nishi Avatar asked Nov 28 '14 07:11

Nishi


People also ask

Does Getchar read EOF?

If the stream is at end-of-file, the end-of-file indicator is set, and getchar() returns EOF. If a read error occurs, errno is set, and getchar() returns EOF.

What is EOF in Getchar?

getchar function takes input from stdin character by character. its stored in a variable c. &that's compared with EOF. EOF stands for END OF FILE. we use this while reading characters from a file.

What is Getchar and EOF in C?

getchar() is a function that reads a character from standard input. EOF is a special character used in C to state that the END OF FILE has been reached. Usually you will get an EOF character returning from getchar() when your standard input is other than console (i.e., a file).

How do I know if my Getchar EOF is 0 or 1?

EOF is End Of File. When we input a character to getchar(), that will be compared with the EOF, and if the input is matching(equal) to that of EOF it will print 1 or else(unequal) it will print 0.


1 Answers

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.

like image 138
Marian Avatar answered Oct 07 '22 08:10

Marian