#include <iostream.h>
#include <string.h>
#include <stdlib.h>
// function prototypes
int compareStringVariables( const void *, const void *);
int compareFloatingPointVariables( const void *, const void *);
void main(void) {
const int buf_size = 100; // maximum input line length
char name[buf_size]; // input buffer for user sentence
char wordArray[50][25]; // 50 words, each 24 long
char * p; // character pointer for strtok
char tok_vals[] = " \t\n.?,"; // separators for strtok
int wordsFound = 0; // number of user words found
int i; // index variable
// Notice that the output buffer is flushed.
cout << "\n Enter some words (each word max 24 characters):" << endl;
cin.getline(name, buf_size); // get the input line
// tokenize the input sentence
// strtok places a NULL terminator in front of the token, if found
p = strtok(name, tok_vals);
while(p != NULL) {
// put words into word array
strcpy(wordArray[wordsFound],p);
wordsFound++;
// Subsequent calls to strtok using a NULL as the first parameter
// returns a pointer to the character following the token
p = strtok(NULL, tok_vals);
}
// verify word count
cout << endl << "You have input " << wordsFound << " words" << endl;
// sort the list of words
qsort((void *)wordArray,
wordsFound,
sizeof(wordArray[0]),
compareStringVariables);
// print out list of sorted words
cout << "List of sorted wqords" << endl;
for(i = 0; i < wordsFound; i++) {
cout << wordArray[i] << endl;
}
// get some floating point values from the user
float theValues[100];
int valueCount = 0;
cout << endl << "Give me some floating point values, 0.0 to end" << endl;
cin >> theValues[valueCount];
while(theValues[valueCount] != 0) {
valueCount++;
cin >> theValues[valueCount];
}
// verify value count
cout << endl << "You have input " << valueCount << " values" << endl;
// sort the list of values
qsort((void *)theValues,
valueCount,
sizeof(theValues[0]),
compareFloatingPointVariables);
// print out list of sorted values
cout << "List of sorted words" << endl;
for(i = 0; i < valueCount; i++) {
cout << theValues[i] << endl;
}
}
int compareStringVariables( const void *a, const void *b) {
// This comparison function must return a negative value if a is less than b,
// zero if the two are equal, or a positive value if a is greater than b. Two array
// elements that are equal can appear in the sorted array in either order.
return( strcmp((char *)a,(char *)b) );
}
int compareFloatingPointVariables( const void *a, const void *b) {
// This comparison function must return a negative value if a is less than b,
// zero if the two are equal, or a positive value if a is greater than b. Two array
// elements that are equal can appear in the sorted array in either order.
if( *((float *) a) < *((float *) b)) return -1;
if( *((float *) a) > *((float *) b)) return 1;
else return 0;
}
* source code is here.