Very simple C program not doing anything (character counting)

  • Thread starter Thread starter bakin
  • Start date Start date
  • Tags Tags
    Counting Program
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 2K views
bakin
Messages
55
Reaction score
0

Homework Statement


Code:
#include <stdio.h>
main()
{
    long nc;

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


Homework Equations





The Attempt at a Solution



I'm trying to learn C and am using the book "C Programming Language". It says that the above program counts characters. But, when I run it and enter something, it just skips down to the next line without doing anything. There's a similar code in the next section that counts lines, and it does the same thing. Am I missing something?
 
Physics news on Phys.org
You are probably trying this on a machine without a raw terminal.
On windows (in a cmd prompt) or any unix shell it will buffer a line of text before sending it to the program.

Try typing something and then doing ctrl-z (windows) or ctrl-D (unix) to signal end of file and send the input to your program.

On unix you can set the terminal to raw mode for this example, it's a bit confusing but worked perfectly well with a raw teletype in 1979 when C was written.