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;
}