gpt4 book ai didi

c - 从文件读取到二叉搜索树时的额外换行符

转载 作者:太空宇宙 更新时间:2023-11-04 04:47:29 24 4
gpt4 key购买 nike

我在 C 中有一个作业,我正在为我从文件中读取的单词创建二叉搜索树。
我的问题是有一些换行符我无法捕获和删除,因此它们被插入到我的二叉树中,当我打印出来时它看起来很奇怪。这也使得某些单词出现多次,因为在使用 strcasecmp 时“yellow\n”与“yellow”不同。

有人对我做错了什么有什么建议吗?

二叉搜索树的输出(中间的额外\n不应该存在!double with 也不是,其中一个在我读取的文件中以换行符结束):

使用
用过的

随便


** 编辑**添加了文件读取。我使用 fgets

typedef struct node {
char word[64];
struct node *left;
struct node *right;
} Tree;

Tree* createTree(char *word){
Tree* current = root;
current = malloc(sizeof(Tree));
strcpy(current->word, word);
current->left = NULL;
current->right = NULL;
return current;
}

void insertBranch(char* word){
Tree *parent = NULL, *current = root, *newBranch = NULL;
int res = 0;

if (root == NULL) {
if(word[sizeof(word) - 1] == '\n')
word[sizeof(word) - 1] = '\0';
root = createTree(word);
return;
}
for(current = root; current != NULL; current = (res > 0) ? current->right : current->left){
res = strcasecmp(current->word, word);

if(res == 0)
return;
parent = current;
}
newBranch = createTree(word);
res > 0 ? (parent->right = newBranch) : (parent->left = newBranch);
return;
}

void readFile(char* chrptr){
char buffer[200];
FILE *file = fopen(chrptr, "r");

if(file == NULL){
printf("Error opening file\n");
return;
}
char *p, *newStr;
while((p = fgets(buffer, sizeof(buffer), file)) != NULL){
newStr = strtok(p, "\",.-<>/;_?!(){}[]:= ");

while(newStr != NULL){

insertBranch(newStr);
newStr = strtok(NULL, "\",.-<>/;_?!(){}[]:= ");
}
}
fclose(file);
}

最佳答案

由于 \n 的作用类似于分隔符而不是单词的一部分,因此将 \n 添加到分隔符列表中。

const char *delims = "\",.-<>/;_?!(){}[]:= \n";  // added \n
char *p, *newStr;
while((p = fgets(buffer, sizeof(buffer), file)) != NULL){
newStr = strtok(p, delims);
while(newStr != NULL){
insertBranch(newStr);
newStr = strtok(NULL, delims);
}
}

关于c - 从文件读取到二叉搜索树时的额外换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19526232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com