我有一个程序旨在读入单词并将它们分开,将每个单词分开并单独计数(标点符号不同的单词被故意算作不同的单词)。
typedef struct word
{
char letters[100];
int count;
} Word;
int compare (const void *a, const void *b)
{
return strcmp((*(struct word **) a)->letters,(*(struct word **) b)->letters);
}
int main()
{
int sizeCheck = 0;
Word ** collection = malloc(sizeof(Word*));
Word * array = malloc(sizeof(Word));
FILE *fptr, *fout;
char fileName[80];
char fileNameWords[80];
char wordLine[100];
strcpy(fileName,"data");
strcpy(fileNameWords,fileName);
strcat(fileNameWords,"data.out.txt");
操作开始的地方,假设打开文件一切正常(为简短起见已删除):
int wordExists = 0;
int t1 = 0;
char tw1[100];
fscanf(fptr,"%s",wordLine);
strcpy(array->letters,wordLine);
array->count = 1;
collection[sizeCheck] = array;
sizeCheck++;
while (!feof(fptr))
{
wordExists = 0;
fscanf(fptr,"%s",wordLine);
for (t1 = 0; (t1 < sizeCheck) && (wordExists == 0); t1++)
{
strcpy(tw1,array[t1].letters);
if (strcmp(tw1,wordLine) == 0)
{
array[t1].count += 1;
wordExists = 1;
}
}
if (!wordExists)
{
collection = realloc(collection,(sizeCheck+1)*sizeof(Word*));
array = realloc(array,(sizeCheck+1)*sizeof(Word));
strcpy(array[sizeCheck].letters,wordLine);
array[sizeCheck].count = 1;
collection[sizeCheck] = array;
sizeCheck++;
}
}
qsort(collection,sizeCheck,sizeof(Word*),compare);
for (t1 = 0; t1 < sizeCheck; t1++)
{
fprintf(fout,"%s - %d\n",array[t1].letters,array[t1].count);
}
free(collection);
}
}
fclose(fptr);
fclose(fout);
return 0;
}
使用指针到指针的方法,它在大多数情况下都有效,除了涉及 qsort 函数或底部附近的 fprintf 部分时。在这一点上我有点难过。我在这里做错了什么阻止它输出排序的文件? (按词首排序)
最佳答案
只有 collection
数组(指针数组)正在排序。它们指向的值(array
的元素)没有改变。由于您 fprintf
array
的元素,因此您不会看到任何更改。
如果你想对array
进行排序,你可以使用qsort
:
qsort(array, sizeCheck, sizeof(Word), compareWord);
compareWord
在哪里
int compareWord(const void *a, const void *b) {
const Word *wa = a;
const Word *wb = b;
return strcmp(a->letters, b->letters);
}
或者,只打印出 collection
而不是 array
中的元素:
fprintf(fout, "%s - %d\n", collection[t1]->letters, collection[t1]->count);
关于C qsort 不对结构数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22948427/