I'm learning C following the book "The C Programming Language" - K&K; I found myself stuck in the understanding of the role of else if (state == OUT)
:
#define IN 1
#define OUT 0
main ()
{
int c, nw, state;
state = OUT;
nw = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf ("%d", nw);
}
In the word counting program, I mean, in the way I read it there must be something I am doing wrong, because I fail to understand why this makes the difference, from simple else
, since state = OUT
is already default condition; but in practice I observe that it does, because if I write just else
then the statement state = IN; ++nw
will count characters and not words;
from the way I read it, the loop is saying that for each input character (stored in the variable c), if it is a space, a new line, or a tab, then it's value is zero, everything else, will be 1, so I fail to see how it is grouping characters into words, because state
was OUT
already before the loop, so how is else if (state == OUT)
getting the program to put the characters into one word?
I have been thinking whole night about it but I couldn't find an answer in my thoughts, nor in the book
Aucun commentaire:
Enregistrer un commentaire