4

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?

Nicolas
  • 75
  • 4
  • 1
    Please describe *exactly* what *"Isn't working"* means. Does your program compile? When you run it, what input do you give it? What do you expect to happen? – abelenky Dec 27 '13 at 00:29

4 Answers4

9

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.

vahid abdi
  • 9,636
  • 4
  • 29
  • 35
mcleod_ideafix
  • 11,128
  • 2
  • 24
  • 32
3

as an addition to the answers that were mentioned , here's how to make your program show results when pressing Enter

 #include <stdio.h>

main()
{
   long nc;

   nc = 0;
   while (getchar() != '\n')
          ++nc; 
   printf("%ld\n",nc);
 }
Farouq Jouti
  • 1,657
  • 9
  • 15
1

getchar() is buffered input. Since it is buffered, The control will wait until you press Enter key from the keyboard. In your program, you are checking for EOF by doing

while (getchar() != EOF)

On windows, if you want EOF, you have to input a combination of 2 keys. i.e Ctrl+Z. If you are on LINUX, then EOF is combination of 2 keys Ctrl+D

As said earlier, control will wait at console until you press Enter, so you have to press

  • Ctrl+Z Enter - on windows.
  • Ctrl+D Enter - on LINUX.
vahid abdi
  • 9,636
  • 4
  • 29
  • 35
0

You have to send EOF to program by pressing CTRL+D (for linux) or CTRL+Z (for Windows) to end the while loop.

vahid abdi
  • 9,636
  • 4
  • 29
  • 35
Mehrdad
  • 708
  • 1
  • 17
  • 38