getchar() in c while using it

182 views Asked by At
main ()
{
    int c;
    while ((c = getchar()) != EOF)
    {
      putchar(c);
    }
}

I know that getchar() buffers the character. If i execute this program and input some character like Hello and without pressing enter I pressed EOF character why it printing Hello again and asking for new character?

4

There are 4 answers

0
Jonathan Leffler On BEST ANSWER

When you type the 'EOF' character, the terminal driver makes all the characters in the input buffer available to the program, even if you've not typed a newline. Since the code underneath getchar() got some characters, it wasn't at EOF yet. When you type the second 'EOF', there are no characters left to be sent (but the terminal driver lets the read() function know there were 0 bytes available), so the read gets 0 bytes returned, which indicates EOF.

1
jester On

This is because your program doesn't receive input from the shell until you have entered a full line. Till then it is stored in the terminal program's buffers. By default, the terminal will buffer all information until ENTER is pressed, before even sending it to the C program.

2
learning On

If you're using Linux and probably gcc then you have to press ctrl+D for EOF. And of course press it twice if you're not pressing enter after entering few characters.

0
Ned On

Just as getchar fills a buffer and then "reads" a character at a time, putchar does the same thing when printing characters. To perform character at a time I/O, you need to open the input and output streams in an unbuffered mode. However, that can be very inefficient, particularly if program input and output are being read and written directly to and from files or pipes. Instead, work with buffered input and output when possible or put in explicit calls to flush any output streams whenever you really need the output to be written whether the I/O buffer is full or not.