Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is getchar() not working for me?

Tags:

c

getchar

I've just started programming c and I'm working through The C Programming Language by Brian W.Kernighan and Dennis M.Richie.

One of the first examples is character counting and the following program is given, but when I enter a string no result it printed.

#include <stdio.h>

main()
{
   long nc;

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

Why isn't this working?

like image 701
Nicolas Avatar asked Dec 12 '22 08:12

Nicolas


1 Answers

You have to finish the input. Your program will count characters until EOF is encountered. EOF, in the keyboard, can be sent by pressing Ctrl-Z then ENTER if you are in Windows, or Ctrl-D then ENTER if you are in Linux/OS X.

like image 195
mcleod_ideafix Avatar answered Dec 26 '22 16:12

mcleod_ideafix