1

I am currently running this character counting .c but the EOF is not reached unless I press control D, which is very annoying.

#include <stdio.h>
main () {

   long nc;

   nc = 0;

   while (getchar() != EOF) {
       ++nc;
   }

   printf("%ld\n", nc);

}
Harry Yang
  • 23
  • 4

1 Answers1

3

What you are seeing is the expected behavior.

EOF is encountered only when the input stream ends. What you are doing (I suppose) is press the enter key. That doesn't signal EOF, because you could type in more stuff after the enter. Ctr+D signals the end of a file.

What you can do is look for End Of Line. And you also need to look for EOF since the user can terminate by pressing Ctr+D (as suggested by @DavidC.Rankin)

This can be done by matching getchar() with '\n' and EOF as

int c
while ((c = getchar()) != '\n' && c != EOF) {
    ++nc;
}

Hope this helps.

Ajay Brahmakshatriya
  • 8,993
  • 3
  • 26
  • 49
  • What happens if the user presses `Ctrl+d` (or `ctrl+z` on windoze)? (you need to check both `'\n'` && `EOF`) (e.g. `int c; while ((c = getchar()) != '\n' && c != EOF) ...`) – David C. Rankin Jun 16 '17 at 06:34
  • @DavidC.Ranakin, oh yes. I will fix it. – Ajay Brahmakshatriya Jun 16 '17 at 06:38
  • @DavidC.Rankin: You have to check both like this: `char readChar; while ((readChar = getchar()) != EOF && readChar != '\n') { ... }` – Andre Kampling Jun 16 '17 at 06:38
  • Only if your implementation defines `EOF` as type `char`, otherwise `EOF` (`-1` generally) will never be seen on a little-endian box. – David C. Rankin Jun 16 '17 at 06:39
  • @DavidC.Rankin, corrected! Also is that fancy spelling for "windoze" intentional? :p – Ajay Brahmakshatriya Jun 16 '17 at 06:45
  • 1
    (tongue-in-cheek) yep, it's just a light-hearted dig at the windows crowd. (I don't have anything against any OS, but do prefer not to rent software...) – David C. Rankin Jun 16 '17 at 06:47
  • @AndreKampling See: See: [**Comparing unsigned char and EOF**](https://stackoverflow.com/questions/8586722/comparing-unsigned-char-and-eof) for an explanation of why it should be `int` . (because `getchar` reads each char as an `unsigned char` cast to an `int` which would result in the comparison of `if (0x000000ff == 0xffffffff)` in your case) – David C. Rankin Jun 16 '17 at 06:57
  • @DavidC.Rankin: Thank you for your hint! – Andre Kampling Jun 16 '17 at 06:59