0

I am reading The C Programming Language (K & R) and playing with the code having some hard time understanding behavior of getchar() function and related EOF macro. Environment: Windows 10 (Ctrl-Z as EOF).

Here's a very simple code snippet I'm playing with:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main() {
    printf("Enter something:\n");
    int c;
    while ((c = getchar()) != EOF) {
        putchar(c);
    }
    printf("End\n");
}
  1. When I run it and input something it works very well (simple duplicate of the input):
Enter something:
hello world
hello world
a
a
a
a
  1. However, when I provide some input with EOF (Ctrl-Z) at the end, the loop doesn't end for some reason, I've got a right arrow character. Why is that so?
Enter something:
hellow world^Z
hellow world→

Doesn't C have to read each single character and find Ctrl-Z to end the loop?

  1. In order to end the loop I have to provide Ctrl-Z on the separate line:
Enter something:
hellow world^Z
hellow world→^Z
End

or:

Enter something:
hello world     
hello world     
^Z              
End
  1. What really bizarres me is a situation when I provide Ctrl-Z at the middle of the input - only a half of the input is printed:
Enter something:
hello^Zworld
hello→

And loop doesn't stop.

I would really appriciate any description of the provided behavior.

P.S: please, do not mark this post as duplicate. I know that there are tonn of similar discussions on this topic, but all of them don't really answer my questions.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
CuriousPan
  • 783
  • 1
  • 8
  • 14

0 Answers0