【发布时间】:2014-05-21 19:43:06
【问题描述】:
我有一个程序,旨在读取单词并将它们分开,将每个单词分开并单独计数(故意将标点符号不同的单词计为不同的单词)。
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 部分。在这一点上,我有点难过。我在这里做错了什么,阻止了它输出排序的文件? (按单词拼音排序)
【问题讨论】:
标签: c arrays sorting structure