Search code examples
cinputeofgetchar

Getchar() infinite loop


I’m starting to learn from "The C Programing Language" and one of the codes in the book is not working for me. This code suppose to count the number of characters using getchar().

Here is my code:

#include <stdio.h>

int main()
{
  long nc;

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

  return 0;
}

I try to run it and write some characters but when I press ENTER, it only starts a new line. It's like it’s never getting out of the loop.


Solution

  • A newline is not an EOF. You’re confusing EOF and EOL.

    When your press ENTER, getchar() receives a newline: \n, and your program counts it just like any other character.

    Try pressing CTRL + D (Linux terminal) or CTRL + Z (Windows terminal) to send an empty input to your program, thus ending it.

    You can also write your input to a file, and give this file to your program as input, like this:

    ./your_program < your_file
    

    When your input comes from a file, an EOF is automatically sent to your program when reaching the end of the file. That’s because there is not more output to get from the file.