Search code examples
chashtablesingly-linked-listcs50

Speller works for some words not others. Dont know where the problem is


I am CS50 problem set 4, speller, hashtable version.

Code detects number of words correctly in dictionary and text. However it mis-spells words.

// Loads dictionary 
bool load(const char *dictionary)
{
    // Initialize hash table
    for (int i = 0; i < N; i++)
    {
        hashtable[i] = NULL;
    }

    // Open dictionary
    FILE *file = fopen(dictionary, "r");
    if (file == NULL)
    {
        unload();
        return false;
    }

    // Buffer for a word
    char word[LENGTH + 1];

    // Insert words into hash table
    while (fscanf(file, "%s", word) != EOF)
    {
        node *new_node = malloc(sizeof(node));
        int j = hash(word);

        // check if out of memory
        if (new_node == NULL)
        {
            unload();
            return false;
        }
        else
        {
            strcpy(new_node->word, word);
            new_node->next = hashtable[j];
            hashtable[j] = new_node;
            }
        }
    }

    fclose(file);
    return true;
}

// Returns number of words in dictionary if loaded 
{
    unsigned int count = 0;
    for(int i = 0; i < 26; i++)
    {

        node *cursor = hashtable[i];
        while (cursor != NULL)
        {
            cursor = cursor->next;
            count++;
        }
     }
    return count;
}


 // Returns true if word is in dictionary else false
bool check(const char *word)
{
    int i = hash(word);
    node *chk = hashtable[i];

    while (chk != NULL)
    {
        if (strcmp(chk->word, word))
        {
            return true;
        }
        chk = chk->next;
    }
    return false;
}

// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
    // TODO

    for (int i = 0; i < N; i++)
    {
        node *cursor = hashtable[i];

        while (cursor != NULL)
        {
            node *temp = cursor;
            cursor = cursor->next;
            free(temp);
        }
    }
return true;
}

If large dictionary is selected, misspelled words are always 0 (whatever the text is), if small dictionary is selected (with cat.txt), it was showing as expected. Any custom made dictionary, shows some correct words as misspelled words.


Solution

  • From man strcmp [emphasis added]:

    RETURN VALUE
    The strcmp() and strncmp() 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.

    You could take a small custom made dictionary through debug50 and see what happens at this line:
    if (strcmp(chk->word, word))

    Since strcmp returns an int, test it like an int, not a bool. And don't forget: the checker should be case insensitive!