I am supposed to write a program to print a histogram of the lengths of words in its input. When I compile my current code I get some random output... Any ideas how to solve this problem?
Ok guys… I tried to take into account your suggestions, so here is what I came up with so far:
#include <stdio.h>
#define OUT 0
#define IN 1
int main()
{
int c, i, j, state, word, wlen;
word = wlen = 0;
state = OUT;
int length [20];
for (i=0; i<20; ++i) {
length[i] = 0; // initialize elements
i = 0;
}
while ((c = getchar()) != EOF && word < 20) {
if (c == ' ' || c == ' ' || c == '
')
{
state = OUT;
}
else if (state == OUT)
{
++word;
state == IN;
}
else if (word == OUT)
{
state = IN;
++word;
++length[wlen];
}
else if (state == IN)
{
++length[wlen];
}
}
printf( "histogram:");
for (i=0; i<20; ++i) {
printf( "%2d", i);
for (j = 0; j < length[i]; ++j)
printf("*");
printf("
");
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…