我正在用“The C Programming Language”一书学习 C,我正在尝试解决练习 1.13:
“编写一个程序来打印输入中单词长度的直方图。用水平条绘制直方图很容易;垂直方向更具挑战性。”
我编写了代码,但是当我按 CTRL+Z(文件结尾)时,它显示全零而不是单词的长度。
谁能给我一个提示我哪里出错了?
#include <stdio.h>
/* print a histogram of the length of words from input */
main()
{
int c, i, wordn, space;
int lengthn[20];
wordn = space = 0;
for (i = 0; i < 20; ++i)
lengthn[i] = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\t' || c == '\n')
if (space == 1) {
++wordn;
space = 0;
++i;
}
if (c != ' ' && c != '\t' && c != '\n') {
++lengthn[i];
space = 1;
}
}
printf("Length: ");
for (i = 0; i < 16; ++i)
printf("%d ", lengthn[i]);
printf("\n --------------------------------------------------------------\n");
printf("Word: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n");
}