cclioneofansi-ckernighan-and-ritchie

Triggering EOF From Keyboard Input (Terminal)


I'm a new[er] programmer and going through K&R's "ANSI C" 2nd edition book. The example has the following program that counts characters using getchar() until EOF is reached.

include <stdio.h>

int main()
{
    double nc;

    for (nc = 0; getchar() !=EOF; ++nc)
        ;
    printf("%.0f\n", nc);
}

After compiling and running (using Notepad and Terminal), I can input "123456789", hit enter (nothing happens), then input Ctrl+Z, then hit enter again, and the program terminates with a result of 10 (reasonable outcome, but I'm unsure if it counted the 10th character as the Ctrl, the "Z", the "Ctrl+Z", or the Enter key... I suspect it's the Enter key). If I try inputting "123456789CtrlZ" + "Enter", nothing happens. If my only input is "Ctrl+Z" then "Enter", the program terminates with a result of 0 (expected).

I am also running this program in CLion, but I cannot satisfy EOF and I have to manually abort the program and therefore I never get a character count (I've tried Ctrl+Z, Ctrl+D, Enter, ESC, combinations of all, etc.)

This topic is somewhat covered here, which helps, but doesn't quite satisfy my question. I know I don't need to know the actual value of EOF (which prints as "-1"). This is more of a practical question about how this program executes. I assume the for loop doesn't execute until I hit "Enter" after inputting a string of characters, but:

  1. Why doesn't "123456789CtrlZ" + "Enter" result in a main() fully executing with an output of 9?

Appreciate any wisdom on this. I'm trying not to move forward in the book unless I fully understand each example.

Edit with data to support the answer below:

enter image description here


Solution

  • Why doesn't "123456789CtrlZ" + "Enter" result in a main() fully executing with an output of 9?

    Because Ctrl-Z anywhere but first on a line places its regular value in the input buffer (and then skips the rest of the line until you press Return). Ctrl-Z has value 26 in the Windows world and the special case EOF has value -1.

    However, when you press Ctrl-Z first on a line, it places EOF in the input buffer. Since input is line buffered, you'll then have to press Return to get the EOF. A session could then look like this:

    hello world<Return>
    this is fun<Return>
    <Ctrl-Z><Return>
    

    Output:

    24
    

    The first two Return keystrokes in the example will be counted.