【发布时间】:2019-04-02 06:55:30
【问题描述】:
我想阅读一些不同类别的文本文件并建立一个链表,其中包含来自这些文本文件的不同单词以及这些单词在文本文件中出现的总次数。链表应按字母顺序排列。但是当我运行代码时,只打印了三个不同的单词数百次,它们的出现值始终为 1。阅读所有单词没有问题。我通过在 while 循环中添加 printf 语句对其进行了测试,它可以正确打印所有单词。我猜insert函数有问题。
#include <stdio.h>
#include <stdlib.h >
#include <locale.h>
typedef struct Term {
char * termName;
int occur;
struct Term * next;
} term;
term * insert(term * root, char * word);
int main (void) {
setlocale(LC_ALL, "Turkish");
FILE *fPtr;
int counter = 1;
char path[50];
snprintf(path, sizeof(path), "dataset\\econ\\%d.txt", counter);
term * terms;
terms = NULL;
while (fPtr = fopen(path, "r")) {
while(!feof(fPtr)) {
char word[20];
fscanf(fPtr, "%s", &word);
terms = insert(terms, word);
}
fclose(fPtr);
counter++;
snprintf(path, sizeof(path), "dataset\\econ\\%d.txt", counter);
}
counter = 1;
snprintf(path, sizeof(path), "dataset\\health\\%d.txt", counter);
while (fPtr = fopen(path, "r")) {
while(!feof(fPtr)) {
char word[20];
fscanf(fPtr, "%s", &word);
terms = insert(terms, word);
}
fclose(fPtr);
counter++;
snprintf(path, sizeof(path), "dataset\\health\\%d.txt", counter);
}
counter = 1;
snprintf(path, sizeof(path), "dataset\\magazin\\%d.txt", counter);
while (fPtr = fopen(path, "r")) {
while(!feof(fPtr)) {
char word[20];
fscanf(fPtr, "%s", &word);
terms = insert(terms, word);
}
fclose(fPtr);
counter++;
snprintf(path, sizeof(path), "dataset\\magazin\\%d.txt", counter);
}
fclose(fPtr);
while (terms -> next != NULL) {
printf("%s: %d\n", terms -> termName, terms -> occur);
terms = terms -> next;
}
}
term * insert(term * root, char * word) {
if (root == NULL) {
root = (term *)malloc(sizeof(term));
root -> next = NULL;
root -> termName = word;
root -> occur = 1;
return root;
} else if((strcmp(root-> termName, word)) < 0) {
term * temp = (term *)malloc(sizeof(term));
temp -> termName = word;
temp -> occur = 1;
temp -> next = root;
return temp;
} else {
term * iter = root;
while ((iter -> next != NULL) && (strcmp(iter -> termName, word) >
0)) {
iter = iter -> next;
if (strcmp(iter -> termName, word) == 0) {
iter -> occur += 1;
return root;
}
}
term * temp = (term *)malloc(sizeof(term));
temp -> next = iter -> next;
iter -> next = temp;
temp -> termName = word;
temp -> occur = 1;
return root;
}
}
【问题讨论】:
标签: c linked-list