So after putting together this program, I am trying to sort multiple words alphabetically using qsort (). I have been using examples of qsort () found on the web and trying to adapt them to my cause, but all I've done so far is confuse myself. There are no errors, but it crashes when I run it.
Can anyone help?
#include <iostream>
#include <iomanip>
#include <search.h>
#include <string.h>
#include <cctype>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
const int MAX = 100;
int compare(const void* pnum1, const void *pnum2);
void main()
{
int i=0;
int length;
char *delim = " ";
char *token;
char string[MAX];
char* array[255] = {0}; // assume max of 255 pointers
cout << "Please enter a sequence of words. Press enter when completed" << endl;
cin.getline(string, MAX);
length = strlen (string);
while (i < length)
{
string[i] = tolower(string[i]);
i++;
}
cout << "Lower case the words are:\n"
<< string << endl;
token = strtok(string, delim);
int c = 0;
while (token != NULL)
{
cout << "token " << c << " is " << endl << token << endl;
array[c] = token;
token = strtok(NULL,delim);
c++;
}
qsort(array[c], length, sizeof(int), compare);
cout << "\n\nThe alphabetized words are:\n";
for (i = 0; i < length; i++)
{
cout << array [i] << endl;
}
}
int compare(const void* pnum1, const void *pnum2)
// compares two numbers, returns -1 if first is smaller
// returns 0 is they are equal, returns 1 if first is larger
{
int num1, num2;
num1 = *(int *)pnum1; // cast from pointer to void
num2 = *(int *)pnum2;
if(num1 < num2)
return -1;
else
if (num1 == num2)
return 0;
else
return 1;
}
Thanks, I'm fried :(