我写了以下内容来尝试使用 qsort() 函数。我的目标是输入几行文本并打印每个单词的字母列表。每次我运行这段代码时它都会崩溃,我不确定为什么或如何修复它。我还需要添加一些东西来计算单词出现的次数并打印出来,但我不太确定该怎么做。任何建议都会非常有帮助。谢谢!
#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;
}