Search code examples
cwindowseofgetchar

Using EOF and getchar() for character counting in C


Possible Duplicate:
Why doesn't getchar() recognise return as EOF in windows console?

I'm new in C and trying to figure out how EOF and getChar() works.

#include <stdio.h>

main()
{

int number = 0;
while(getchar() != EOF)
     number++;

printf("%d", number);
}

When I type some random characters, the program doesn't do anything, I think that it never gets out of that while loop. Why is that? I'm using CodeBlocks on Windows 7.


Solution

  • Because you aren't sending an EOF character. "EOF" stands for "end-of-file"; console input (known as "standard input") is a special case of a file. But in order to denote that this special file has ended, you need to send a special signal. You can get this effect on Windows by pressing Ctrl+Z (followed by Enter, for some reason).