Very simple C program not doing anything (character counting)

  • Thread starter Thread starter bakin
  • Start date Start date
  • Tags Tags
    Counting Program
AI Thread Summary
The C program provided is intended to count characters from input until an EOF (End of File) signal is received. Users may experience issues where input appears to be ignored due to line buffering in terminal environments, particularly on Windows and Unix systems. To properly signal EOF and execute the program, users should input text followed by Ctrl-Z (Windows) or Ctrl-D (Unix). Additionally, setting the terminal to raw mode can help avoid confusion during input. Understanding these terminal behaviors is crucial for the program to function as intended.
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.
 
Back
Top