Harry Yang
Harry Yang

Reputation: 23

EOF does not work in Mac Xcode (C)?

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);

}

Upvotes: 1

Views: 1867

Answers (1)

Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

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.

Upvotes: 3

Related Questions