我指的是学习C的K和R书; 关于在Word计数程序中使用EOF的while循环,本书中给出的程序运行正常,但我想知道它如何在一次输入后停止输入并给出输出行,单词和&字符数。在这个程序之前,我习惯按Ctrl + Z,然后输入以获得输出,而使用!= EOF循环时。
请帮助我理解这个程序究竟发生了什么,以打破循环。
附加代码和输出 -
#include<stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and charaters in input */
main()
{
int c, n1, nw, nc, state; /* n1 for line count, nw for word count, & nc for character count */
state = OUT;
n1 = nw = nc = 0;
while ( ( c = getchar() ) != EOF ){
++nc;
if ( c == '\n')
++n1;
if ( c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if ( state == OUT) {
state = IN;
++nw;
}
printf ( "%d %d %d \n", n1, nw, nc);
}
}
输出 -
答案 0 :(得分:1)
循环尚未结束。您可以验证这是输入更多字符并按Enter键。您会看到更多输出。这是因为printf
:
printf ( "%d %d %d \n", n1, nw, nc);
in 循环。它将在循环的每次迭代中执行。
如果您希望在之后看到输出,则使用 CTRL + Z 和输入发送EOF
,移动{ {1}}在循环之外。