Search code examples
linked-listhashtablecs50

Cs50 speller: not recognising any incorrect words


I'm currently working on the CS50 Speller function. I have managed to compile my code and have finished a prototype of the full program, however it does not work (it doesn't recognise any mispelled words). I am looking through my functions one at a time and printing out their output to have a look at what's going on inside.

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
    char word[LENGTH + 1];
    int counter = 0;
    FILE *dicptr = fopen(dictionary, "r");

    if (dicptr == NULL)
    {
        printf("Could not open file\n");
        return 1;
    }

    while (fscanf(dicptr, "%s", word) != EOF)
    {
        printf("%s", word);
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            unload();
            printf("Memory Error\n");
            return false;
        }

        strcpy(n->word, word);
        int h = hash(n->word);
        n->next = table[h];
        table[h] = n;
        amount++;

    }
    fclose(dicptr);
    return true;
}

From what I can see this works fine. Which makes me wonder if the issue is with my check function as shown here:

bool check(const char *word)
{

    int n = strlen(word);

    char copy[n + 1];

    copy[n] = '\0';

    for(int i = 0; i < n; i++)
    {
        copy[i] = tolower(word[i]);
        printf("%c", copy[i]);
    }
    printf("\n");
    node *cursor = table[hash(copy)];
    while(cursor != NULL)
    {
        if(strcasecmp(cursor->word, word))
        {
            return true;
        }
        cursor = cursor->next;
    }

    return false;
}

If someone with a keener eye can spy what is the issue I'd be very grateful as I'm stumped. The first function is used to load a the words from a dictionary into a hash table\linked list. The second function is supposed to check the words of a txt file to see if they match with any of the terms in the linked list. If not then they should be counted as incorrect.


Solution

  • This if(strcasecmp(cursor->word, word)) is a problem. From man strcasecmp:

    Return Value
    The strcasecmp() and strncasecmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

    If the words match, it returns 0, which evaluates to false.