#include <stdio.h>
#define IN 1 // in the code below, whenever you see IN, it's replaced by 1
#define OUT 0 // same as IN, but for 0
int main(void) {
int nw, c, state; // nw is the number of the words
// c stands for the character we get from input and state is the state that are
// currently.
// init state as OUT
state = OUT;
// init counter to 0
nw = 0;
// while user doesn't give EOF
while ((c = getchar()) != EOF) {
// we found whitespace, newline or tab
if (c == ' ' || c == '\n' || c == '\t')
state = OUT; // put state as OUT,
// so that we do not count them as words
else if (state == OUT) { // enter here only if state is OUT
// Now, we see that we found a letter/number, which means that a word
// was typed by the user.
// set state as IN, so that we remember that we are eating the characters of
// the word given (in the next loops)
state = IN;
// increase the counter of the words
++nw;
}
}
// print the number of words received by the user
printf("%d", nw);
return 0;
}
现在,让我们看一下示例输入:
sam
dad
当然输出(正如你应该从上面的评论中猜到的那样)是:
2
让我们针对输入 sam 逐步运行(有趣的)代码:
// input: "sam" (without the quotes)
while ((c = getchar()) != EOF) { // eat first character, i.e. 's'
/****** 1st execution of the loop ********************/
// 's' is not going into this if
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
// first time we execute the loop so state is OUT,
// thus we enter the loop
else if (state == OUT) {
// set state as IN
state = IN;
// increase the counter of the words
++nw;
}
/****************************************************/
/****** 2nd execution of the loop ********************/
// while loop's getchar() gives as 'a'
// 'a' is not going into this if
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
// state is IN, so we don't go into this loop
else if (state == OUT) {
state = IN;
++nw;
}
/****************************************************/
/****** 3rd execution of the loop ********************/
// same as 2nd, but for 'm'
/****************************************************/
/****** 4rth execution of the loop ********************/
// while loop's getchar() gives as '\n'
// '\n' is going into this if (the c == '\n' is true
if (c == ' ' || c == '\n' || c == '\t')
state = OUT; // state sets to OUT
// we are not going into this if else, since we already entered the above if!
else if (state == OUT) {
state = IN;
++nw;
}
/****************************************************/
/****** 5th execution of the loop ********************/
// while loop's getchar() gives as 'd' (first letter of dad)
// 'd' is not going into this if
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
// state is OUT, so we go into this loop
else if (state == OUT) {
// set state as IN
state = IN;
// increase counter
++nw;
}
/****************************************************/
// and so on :)
}