1. 程式人生 > >C語言K&R習題系列——統計文件中每個單詞所包含的字母個數,以直方圖形式輸出

C語言K&R習題系列——統計文件中每個單詞所包含的字母個數,以直方圖形式輸出

原題:

Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.

這也是我第一個過百行的程式碼(帶註釋,空格什麼的)

主要分兩個部分:輸入和輸出

#include < stdio.h >
 
#define MAXWORDLEN 10
 
main ( void )
{
    int c;
    int wordLen = 0;
    int thisIdx = 0;
    long lengthArray[MAXWORDLEN + 1];
    long thisVal = 0;
    long maxVal = 0;
     
    //initialize
     
    int inspace = 0;
    int firstLetter = 1;
    int done = 0;
     
    for ( thisIdx = 0; thisIdx <= MAXWORDLEN; thisIdx++ )
    {
        lengthArray[thisIdx] = 0;
    }
     
    while ( done == 0 )
    {
        c = getchar();
         
        if ( c == ' ' || c == '\n' || c == '\t' || c == EOF )
        {
            if ( inspace == 0 )
            {
                inspace = 1;
                firstLetter = 0;
                 
                if( wordLen <= MAXWORDLEN )
                {
                    thisVal = ++lengthArray[wordLen - 1];
                     
                    if  ( thisVal > maxVal )
                    {
                        maxVal = thisVal;
                    }
                }
                else
                {
                    thisVal = ++lengthArray[MAXWORDLEN];
                     
                    if  ( thisVal > maxVal )
                    {
                        maxVal = thisVal;
                    }
                }
            }
            if ( c    == EOF )
            {
                done = 1;
            }
        }
        else
        {
            if ( inspace == 1 || firstLetter == 1 )
            {
                wordLen = 0;
                inspace = 0;
                firstLetter = 0;
            }
             
            ++wordLen;
        }
    }


之後為輸出部分

for ( thisVal = maxVal; thisVal > 0; thisVal-- )
      {
            printf ( "%4d  |", thisVal );
            for ( thisIdx = 0; thisIdx <= MAXWORDLEN; thisIdx++ )
            {
                  if ( lengthArray[thisIdx] >= thisVal )
                  {
                        printf ( " * " );
                  }
                  else
                  {
                        printf ( "   " );
                  }
            }
                  printf ( "\n" );
      }
       
      printf ( "      |_" );
      for ( thisIdx = 0; thisIdx <= MAXWORDLEN; thisIdx++)
      {
            printf ( "___" );
      }
      printf ( "\n      " );
      for ( thisIdx = 0; thisIdx < MAXWORDLEN; thisIdx++ )
      {
            printf ( "%3d", thisIdx + 1 );
      }
      printf ( "  >\n" );
      for ( thisIdx = 0; thisIdx < MAXWORDLEN + 2; thisIdx++ )
      {
            printf ( "   " );
      }
      printf ( "  %2d\n", MAXWORDLEN );
}


執行後的測試: