0

I was practicing C program that i read from The C ANSI Programming Language Second Edition I learn about getchar() function.And the book say that getchar() read the character from stdin until newline character or EOF has been reached.And in the book i try to rewrite the program to count character using getchar() function.The code is fine when compiling. The problem is the code unable to display the long of character.

Here is the code:

#include <stdio.h>

int main (void){
   long nc;

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

   return 0;
}

But when i change the EOF to newline character \n the code working as i expected but only display the long of character only one line. After that the code terminate.

My question is what is EOF exactly is and what is the difference between EOF and newline character.

Is there other way to fix this program?

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
harianja
  • 63
  • 2
  • 8

3 Answers3

3

getchar() returns EOF when you get to the end of the file. It returns \n when you get to the end of the line. This is why your loop finishes when it gets to the end of the line if you replace EOF with \n.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • can you explain me why when using `EOF` the program doesn't display the result in other words the long of the input character? – harianja Oct 25 '14 at 12:52
  • 1
    Sorry I don't know what you mean by "the long of character". In the `EOF` version the total number of characters in the file is printed; in the `\n` version the number on the first line is displayed. – M.M Oct 25 '14 at 12:57
1

EOF means End of File and you get that when your getting to the end of a file with getchar(). You get \n when you get to the end of a line.

When you now want it, so that it prints the text again use this:

#include <stdio.h>

int main(void) {
    int c, nc = 0;

    while ((c = getchar()) != '\n') {
        nc++;
        putchar(c);
    }

    printf("%d\n",nc);

    return 0;

}
Rizier123
  • 58,877
  • 16
  • 101
  • 156
1

EOF is the end of file. It does not mean the end of your "long of character". If you just type many characters occupying several lines on the command line screen, the program still does not get the EOF unless you type Ctrl+D simulating the end of file. When you change EOF to "\n", the program requires the end of line. And when you finish the first line, the program get the end of the first line and run. That is why the code works as you expected but only display the long of character only one line.

Yulong Ao
  • 1,199
  • 1
  • 14
  • 22