In order to sort the words, I recommend that you create an array of char *
, in which every element of the array points to a word.
In order to find the start of the words and to make the words properly terminated by a null character, I recommend that you use the function strtok
or strtok_r
.
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORDS 100
//custom compare function for the function "qsort" which does
//nothing else than call the function "strcmp" for comparison
//purposes
int my_compare( const void *a, const void *b )
{
return strcmp( *(const char**)a, *(const char**)b );
}
int main( void )
{
char *words[MAX_WORDS];
int num_words = 0;
char *line = NULL, *p;
size_t len = 0;
ssize_t lineSize = 0;
//prompt user for input
printf( "Please enter words to sort:\n" );
//read one line of input
lineSize = getline( &line, &len, stdin );
if ( lineSize <= 0 )
{
fprintf( stderr, "Input error!\n" );
exit( EXIT_FAILURE );
}
//remove newline character, if it exists
line[strcspn(line,"\n")] = '\0';
//find first word
p = strtok( line, " " );
//loop until no more words are found, processing one word
//per loop iteration
while ( p != NULL )
{
//verify that we are not overflowing the array
if ( num_words == MAX_WORDS )
{
fprintf( stderr, "Too many words for array!\n" );
exit( EXIT_FAILURE );
}
//add pointer to found word to the "words" array
words[num_words++] = p;
//find next word for next loop iteration
p = strtok( NULL, " " );
}
//now we can sort the array
qsort( words, num_words, sizeof *words, my_compare );
//print the sorted words
for ( int i = 0; i < num_words; i++ )
{
printf( "%s\n", words[i] );
}
//cleanup
free( line );
}
For the input
apple orange banana dog cat
this program has the following output:
apple
banana
cat
dog
orange
As you can see, the words were properly sorted.