Why does getchar () not work for me?

I just started c programming, and I work through the C programming language Brian Kernigan and Dennis M. Ritchie.

One of the first examples is character counting, and the following program is provided, but when I enter a line, the result is not printed.

#include <stdio.h>

main()
{
   long nc;

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

Why is this not working?

+4
source share
4 answers

You must complete the entry. Your program will count the characters until it is met EOF. EOF, the keyboard can be sent by clicking Ctrl-Z, then ENTERif you are on Windows, or Ctrl-D, and then ENTERif you are on Linux / OS X.

+10
source

, , Enter

 #include <stdio.h>

main()
{
   long nc;

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

getchar() - . , The control will wait until you press Enter . EOF,

while (getchar() != EOF)

, EOF, . Ctrl+Z. LINUX, EOF Ctrl+D

, , Enter,

  • Ctrl+Z Enter - .
  • Ctrl+D Enter - LINUX.
+1

EOF , CTRL+D ( linux) CTRL+Z ( Windows), while.

0

All Articles