Search code examples
cgetchar

Counting the number of characters in input with getchar() method


I am studying C from The C Programming Language. I have tried to make the following code work:

#include <stdio.h>
int main() {
    int char_count = 0;
    while (getchar() != EOF)
        ++char_count;
    printf("Number of chars are %ld ", char_count);
    return 0;
}

I build and run the code. Then, I enter a random word and press enter. I expect to see a number in the next line, but what happens is that cursor moves to the next line. When I enter a new word same thing happens. What am I missing?

Edit: I expect getchar() to return EOF when the program finishes getting the characters of the first word.


Solution

  • When you are pressing enter/return you are generating \n or \r\n based on the whether you are using unix/osx or windows. You are not generation EOF character.

    To generate EOF character you need to press ^D on unix/osx or ^Z on windows.