私は「Cプログラミング言語」の本で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");
}