以下代码显示出奇怪的行为。如果我按换行符给出输入,那么只有它打印直方图值,否则如果我直接输入 EOF(^Z),它会显示全零。getchar() 函数是否存在问题,它仅在按下换行符时才接受输入。
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
#define MAXLEN 50
/* count lines, words, and characters in input */
main()
{
int c, i, j, nc, state;
int wordlength[MAXLEN];
state = OUT;
nc = 0;
for (i = 0; i < MAXLEN; i++)
wordlength[i] = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
if (state == IN) {
wordlength[nc-1]++;
}
state = OUT;
}
else if (state == OUT) {
//putchar('\n');
state = IN;
nc = 0;
}
if (state == IN) {
++nc;
}
}
for (j = 0; j < MAXLEN; j++)
printf("\n%d - %d",j,wordlength[j]);
for (i = 10; i >= 0; i--) {
for (j = 0; j < MAXLEN; j++)
printf(((wordlength[j] > i)?"|":" "));
printf("\n");
}
}