user1624005
user1624005

Reputation: 1007

Character Counter from "The C Programming Language" Not Working As I Expected

I am reading through "The C Programming Language", and working through all the exercises with CodeBlocks. But I cannot get my character counter to work, despite copying it directly from the book. The code looks like this:

#include <stdio.h>

main(){
    long nc;

    nc = 0;

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

When I run the program, it opens a window I can type in, but when I hit enter all that happens is it skips down a line and I can keep typing, but I think it's supposed to print the number of characters.

Any idea what's going wrong?

Upvotes: 9

Views: 2961

Answers (5)

leegibsonhoward
leegibsonhoward

Reputation: 11

The above answer provided by nujabse is correct. But recently coming across this issue myself and researching the answer, I would like to add why.

Using Ctrl+C tells the terminal to send a SIGINT to the current foreground process, which by default translates into terminating the application.

Ctrl+D tells the terminal that it should register a EOF on standard input, which bash interprets as a desire to exit.

What's the difference between ^C and ^D

Upvotes: 0

nujabse
nujabse

Reputation: 181

I ran into the problem tonight, too. Finally found out that Ctrl-D on Linux worked. You build the source file using cc, and start the program and input a word, then press Ctrl-D twice when finished typing. The number that the program countered will be printed just behind the very word you just typed, and the program terminates immediately. Just like this:enter image description here

Upvotes: 0

drjd
drjd

Reputation: 399

If you want to terminate on EOL (end of line), replace EOF with '\n':

#include <stdio.h>

main(){
    long nc;

    nc = 0;

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

Upvotes: 3

John Bode
John Bode

Reputation: 123468

Enter is not EOF. Depending on your OS, Ctrl-D or Ctrl-Z should act as EOF on standard input.

Upvotes: 2

ruakh
ruakh

Reputation: 183311

This line:

while (getchar() != EOF)

means that it keeps reading until the end of input — not until the end of a line. (EOF is a special constant meaning "end of file".) You need to end input (probably with Ctrl-D or with Ctrl-Z) to see the total number of characters that were input.

Upvotes: 9

Related Questions