Search code examples
cloopsgetchar

Counting number of user input using getchar() gives double the expected result, why?


In the following example, from the book "C programming", when input characters, the program count twice.

main(){

long nc;

nc = 0;
while (getchar() != EOF)
    ++nc;
    printf("%ld\n", nc);
}

OUTPUT:

a
b
c
d
e
f
12

What's wrong?

I'am using Ubuntu and the gcc compiler.


Solution

  • It's counting properly. getchar() is considering the ENTER key press also, as a newline \n. So 6 user inputs and 6 newlines. Counts match.

    If you don't want the newlines to be counted as inputs, you need to increment the counter when the getchar() return value is not \n, something like

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

    will get the job done. Note, c should be of type int to be able to handle EOF.

    That said, as per C99 or C11, for a hosted environment, the signature of main() should at least be int main(void) to conform to the standard.