Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

c - Program to print a histogram of the lengths of words in its input

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your 'or' comparisons should be 'and' comparisons, and your print statements at the end print chars instead of ints — you should use %d not %c. Also, your for loop needs braces if you want that print statement for a newline character to run more than once.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...