简体   繁体   中英

how does this code from “The C Programming Language” work?

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?

Windows uses Ctrl-Z for EOF, and UNIX uses Ctrl-D. See http://bytes.com/groups/c/217873-eof-windows , and excellent book choice. :)

^ Z为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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM