Question

I have an assignment in C where im making a binary search tree for words that i read from a file.
My problem is that there are some newlines what i dont manage to catch and get rid of, therefore they get inserted into my binary tree and it looks all wierd when i print it out. This also make some of the words come up several times as "yellow\n" is different from "yellow" when using strcasecmp.

Does anyone have any suggesteons as to what im doing wrong?

Output from the binary search tree (the extra\n in the middle is not supposed to be there! Neither is the double with, where one ends on a line break in the file i read from)):

use
Used
was

whatsoever
with
with

** EDIT** Added the file-reading. I use 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);
}
Was it helpful?

Solution

Since \n is to act like a delimiter and not part of a word, add \n to delimiter list.

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top