Reputation:
Right now I am going through a book on C and have come across an example in the book which I cannot get to work.
#include <stdio.h>
#define IN 1
#define OUT 0
main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
It's supposed to count the number of lines, words, and characters within an input. However, when I run it in the terminal it appears to do nothing. Am I missing something or is there a problem with this code?
Upvotes: 4
Views: 453
Reputation: 76
I usually handle this kind of input like this (for Linux): 1. make a file (for example, named "input.txt"), type your input and save 2. use a pipe to send the text to your application (here assume your application named "a.out" and in the current directory):
cat input.txt | ./a.out
you'll see the program running correctly.
Upvotes: 0
Reputation: 30442
getchar() returns the input from the standard input. Start typing the text for which you want to have the word count and line count. Your input terminates when EOF is reached, which you do by hitting CTRL D.
CTRL D in this case acts as an End Of Transmission character.
cheers
Upvotes: 1
Reputation: 799130
It's waiting for input on stdin. Either redirect a file into it (myprog < test.txt
) or type out the data and hit Ctrl-D (*nix) or Ctrl-Z (Windows).
Upvotes: 2
Reputation: 10430
The program only terminates when the input ends (getchar returns EOF). When running on terminal, this normally never happens and because of this it seems that the program is stuck. You need to close the input manually by pressing Ctrl+D (possibly twice) on Linux or pressing F6 and Enter at the beginning of the line on Windows (different systems may use different means for this).
Upvotes: 7
Reputation: 5234
What it is doing is entering a loop for input. If you enter a character or newline, nothing happens on the screen. You need to interrupt the process (on my Mac this is CTRL+D) which serves as EOF. Then, you will get the result.
Upvotes: 1
Reputation: 8864
When you run it, you need to type in your text, press return
, then type Ctrl-d
and return
(nothing else on the line) to signify end-of-file. Seems to work fine with my simple test.
Upvotes: 1