K & RC Character Counting

I am working on a K & R book and I find code example on how to read characters from a text stream. I copied their code and tried to run it, but when you ask for characters at the command line, the loop does not exit and therefore will never print the character counter. Is there a mistake here, I will not catch?

#include <stdio.h>

main() 
{
     long nc;
     nc = 0;
     while(getchar() != EOF) {
          ++nc;
     }
     printf("%1d\n", nc);
}
+3
source share
3 answers

Whenever you want to stop it, just send the EOF signal to the shell.

Ctrl+ don Linux or Ctrl+ zon Windows.

By the way (as additional information) Ctrl+ csend SIGINTto the process on Linux and Windows, it does something like that.

+10
source

Ctrl + D ( Linux) Ctrl + Z ( Windows)? , . EOF, .

+2

Try terminating the character stream with CNTL-Z (end of file character). Just pressing Enterleads to CR, which is another character to count

+1
source

All Articles