Reputation: 1
I wrote the following to try to use the qsort() function. My goal is to input several lines of text and print an alphabetical listing of each word. This code crashes every time I run it and i am not sure as to why or how to fix it. I also need to add something to count the number of times a word occurs and print that as well but I an mot too sure how to do that. Any advice would be very helpful. Thanks!
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
struct to_lower
{
int operator() ( int ch )
{
return tolower ( ch );
}
};
int compare (const void * a, const void * b)
{
//return ( *(int*)a - *(int*)b );
return (strcmp(*(const char **)a, *(const char **)b));
}
int main()
{
string list[900];
int nLength;
int i=0, q=0;
string nTemp;
int word[900];
cout
<< "Enter some lines of text "
<< "(Enter Ctrl-Z on a line by itself to exit)\n"
<< endl;
while ( !cin.eof() )
{
cin >> list[i];
transform(list[i].begin(), list[i].end(), list[i].begin(), to_lower());
word[q]=1;
if (list[i]==list[i-1])
{
word[q]=+1;
}
i++;
}
nLength = i;
cout << "The sorted words would be:\n";
qsort(list, nLength, sizeof list[0],&compare);
int n;
for (n = 0; n < nLength; n++)
{
cout <<" \n"<< n << list[n]<< word[n];
}
return 0;
}
Upvotes: 0
Views: 199
Reputation: 54325
std::string
is not a char*
as your qsort compare function pretends. Also, you should never use qsort with C++ objects. qsort does not know about objects and won't call copy constructors and may damage the internal structure.
When i=0, using list[i-1] is a bug.
You need to count your duplicate words after sorting or you have no guarantee that duplicates are next to each other.
Upvotes: 2