Very simple C program not doing anything (character counting)

  • Thread starter Thread starter bakin
  • Start date Start date
  • Tags Tags
    Counting Program
Click For Summary
SUMMARY

The C program provided counts characters from standard input until an End-Of-File (EOF) signal is received. Users may experience issues with input not being processed immediately due to line buffering in environments like Windows Command Prompt or Unix shells. To properly execute the program, users must signal EOF using Ctrl-Z on Windows or Ctrl-D on Unix systems. Additionally, setting the terminal to raw mode can enhance input handling, reflecting the original environment in which C was developed.

PREREQUISITES
  • Understanding of C programming syntax and structure
  • Familiarity with standard input and output functions in C
  • Knowledge of EOF signaling in command-line environments
  • Basic concepts of terminal modes (raw vs. buffered)
NEXT STEPS
  • Learn about character input handling in C using functions like getchar()
  • Explore terminal settings and how to switch between raw and buffered modes
  • Investigate the differences in input handling between Windows and Unix systems
  • Study the C programming book "C Programming Language" for deeper insights into standard I/O
USEFUL FOR

Beginner C programmers, computer science students, and anyone interested in understanding character input processing in command-line applications.

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.
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
11K
  • · Replies 9 ·
Replies
9
Views
4K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 15 ·
Replies
15
Views
3K
Replies
9
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 9 ·
Replies
9
Views
4K
Replies
8
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
1K