Search code examples
cgetchar

Character Count in C


The folllowing C Program is to calculate the character Count .

#include <stdio.h >
int main()
{
   int nc = 0;
   while (getchar() != EOF)
   {
      ++nc;
      printf("%d\n", nc); 
   }
    return 0;
}

When I Enter a character , for example 'y' in the terminal , The output returns as follows

1
2

How does this calculation happens and why 2 is in the output?


Solution

  • I suppose you didn't know but when you press enter you just insert a newline character or '\n'. If you want to get the correct result ignore the newline character or just decrease the nc by one.

    #include <stdio.h>
    
    int main()
    {
      int nc = 0;
      while (getchar() != EOF)
      {
        ++nc;
        printf("Character count is:%d\n", nc - 1);
      }
      return 0;
    }
    

    Even better code:

    #include <stdio.h>
    int main()
    {
      int nc = 0;
      for(;;)
      {
        do
          ++nc;
        while (getchar() != '\n');
        printf("Character count is:%d\n", nc - 1);
        nc = 0;
      }
    }
    

    The updated code will reset your counter back to 0.