0

I just started writing C programs and I am taking help of The C Programming book written by Dennis Ritchie. When I tried to run the program for COUNTING characters or new lines, i was expecting some numbers as solutions but it didn't happen, instead it just allowed me to enter characters, with no value( of the number of lines/ characters) in return. I am new to programming. I would appreciate some help to get me through.

character counting

#include <stdio.h>

main( )
{
      long nc;

      nc=0;
      while (getchar( ) != EOF)
               ++nc;
      printf( "%1d\n",  nc );
}
svick
  • 236,525
  • 50
  • 385
  • 514

2 Answers2

2

As you can see in the line

while (getchar( ) != EOF)

Your program is expecting an EOF (End Of File) before printing the counter.

Therefore you should type your text then Ctrl + D (EOF in a *nix command shell) or Ctrl + Z (Windows) to cut your input.

Then your counter will be printed.

Regards

LiGhTx117
  • 218
  • 2
  • 8
0

Seems like you are confused with sending input to your program. Your code reads characters one by one from so called STDIN until it reads EOF (End-Of-File) marker. Usually STDIN - is a keyboard, so whatever you type appears to be read by getchar(). If you wish to send EOF - press Ctrl+D (unix systems). Another alternative - use prefilled text file and use it as STDIN for your program via redirection:

$ ./a.out < my_input.txt

This approach works well both on *nix and win systems.

Sergio
  • 8,099
  • 2
  • 26
  • 52