2

an example from a book:

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

now this book doesn't explain much but says that getchar() reads the next character input. I believe the reason for c = getchar() before the loop has to do something with input buffers. I have done research on it but still can't wrap my head around it exactly. In this example, removing c = getchar() does not make a difference in how the program functions.

What is the exact reason for c = getchar() before the loop and what does it have to do with the input buffers? Also: How can I input EOF? pressing enter or -1 does not terminate the loop, so in this case I don't understand how the check for EOF is necessary in this case.

Aiden Choi
  • 142
  • 7
  • To signal EOF, type control-Z on Windows or control-D on Mac or Linux. It must be at the beginning of a line. If standard input is a file rather than the terminal window, then the I/O library will return EOF when there are no more characters in the file. It's not a character. – rici May 23 '21 at 22:25
  • And if it is not obvious that `c` does not have a value before you execute `c = getchar()` the first time, and therefore the test to see whether it has a particular value is meaningless, then you are reading too fast. – rici May 23 '21 at 22:30

1 Answers1

0

If you remove c = getchar(); before the loop, the value of c will be indeterminate when the loop is first entered. So this is necessary to have a value to read before printing a character and reading the next one.

To input EOF, you would press either CTRL-D or CTRL-Z depending on whether you're using Linux or Windows.

dbush
  • 205,898
  • 23
  • 218
  • 273