Thread: Program to show the number of occurrences of words...

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020

    Program to show the number of word lengths

    Hi,

    This is a program to take in several lines of text and output the number of one-letter word, two-letter words.....etc. But it didn't work. I think it's because the last word of the sentence got stuck to the first word of the next sentence and become one word. I tried adding a space in between ( maybe i did it the wrong way ) but still didnt' output corectly. Pls give a hand. Thnx in advance.!

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
       int word_length_occurrence[ 20 ] = { 0 };
       char string[ 700 ];
       char tempStr[ 300 ];
       int i, numLines;
       int maxLength = 0;
       char *tokenPtr;
    
       printf( "Number of lines: " );
       scanf( "%d", &numLines );
    
       gets( tempStr ); /* grabs the carriage return */
    
       for ( i = 0; i < numLines; i++ ) {
          gets( tempStr );
          strcat( string, tempStr );
       }
    
       tokenPtr = strtok( string, " " );
    
       while ( tokenPtr != NULL ) {
          word_length_occurrence[ strlen( tokenPtr ) ]++;
          if ( maxLength < strlen( tokenPtr ) )
             maxLength = strlen( tokenPtr );
          tokenPtr = strtok( NULL, " " );
       }
    
       printf( "%8s%15s\n", "Word Length", "Occurrences" );
    
       for ( i = 1; i <= maxLength; i++ )
          printf( "%4d%15d%c", i, word_length_occurrence[ i ], '\n' );
    
       printf( "\n" );
       system("PAUSE");
       return 0;
    }
    Last edited by Nutshell; 01-25-2002 at 03:37 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. prime number program with function
    By mackieinva in forum C Programming
    Replies: 17
    Last Post: 09-20-2007, 08:36 AM
  2. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  3. Number of words multiplied by the number of lines in Linux
    By sjalesho in forum Linux Programming
    Replies: 2
    Last Post: 11-20-2003, 03:25 PM