how does this code from “The C Programming Language” work?
-
23-08-2019 - |
Question
I'm reading "The C Programming Language (2nd ed.) and near the beginning, it has examples like this:
while((c = getchar()) != EOF)
if(c == '\n'){
++n1;
I can see how this would work while reading from a file, and I understand this syntax... But this is just reading from the console--how does one signal end of file when entering characters from a console? I'm using Windows XP... MinGW compiler... Anyways, was this book written for waaay earlier systems with like an EOF button or something?
Update
well, I have one more question, that's just related to how the end-of-file works under Windows.
If I just while(getchar()!=EOF);
, then I can just keep typing characters until I signal EOF via ^Z. But, I have to write a newline, then hit ^Z, then another newline... Why does it have to be on its own line?
Solution
Windows uses Ctrl-Z for EOF, and UNIX uses Ctrl-D. See http://bytes.com/groups/c/217873-eof-windows , and excellent book choice. :)
OTHER TIPS
^Z is EOF.
The correct answer has been already given, but a typical usage would be to redirect a file to standard output:
program.exe < samplefile.txt
samplefile.txt
is "written" to standard out and program.exe
reads this from standard out until the EOF is reached.
Regarding your question on ^Z, the reasonn it behaves like this is because it isn't really a character, it's a signal from the operating system to the C input system. As such, it is highly dependant on the interaction between the OS and the C input system buffering. Which is a fancy way of saying that it's just the way things work, for Windows and for your particular C implementation.