I'm practicing using C & Unix by writing up some of the C programs in Vim and compiling them.
The word count program is supposed to end when the character read is EOF (CTRL-D). However, when I run it, the first CTRL-D pressed just makes it print "^D" (minus the quotes) on the terminal. The second time it's pressed, the "^D" goes away and it terminates normally.
How can I change this so that it terminates after only one CTRL-D? I notice that if I've just made a newline character, then pressing CTRL-D once does the trick. But I don't really understand why it works then and not in the general case.
Here's what the program looks like for those of you who don't have the book.
#include <stdio.h>
#define IN 1 /* Inside a word */
#define OUT 0 /* Outside a word */
int main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n') {
++nl;
--nc;
}
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
nw++;
}
}
printf("%d %d %d\n", nl, nw, nc);
return 0;
}