c - 拼写器适用于某些单词,不适用于其他单词。不知道问题出在哪里

标签 c hashtable singly-linked-list cs50

我是 CS50 问题集 4,拼写器,哈希表版本。

代码正确检测字典和文本中的单词数量。然而它拼写错误。

// 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;
}

如果选择大词典,拼写错误的单词始终为 0(无论文本是什么),如果选择小词典(使用 cat.txt),则按预期显示。任何定制的词典都会将一些正确的单词显示为拼写错误的单词。

最佳答案

来自 man strcmp [添加强调]:

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.

你可以通过 debug50 获取一个小的定制字典,看看这一行会发生什么:
if (strcmp(chk->word, word))

由于 strcmp 返回一个 int,因此请像 int 一样测试它,而不是 bool。并且不要忘记:检查器应该区分大小写!

关于c - 拼写器适用于某些单词,不适用于其他单词。不知道问题出在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57229671/

相关文章:

java - 包名称破坏了 JNI 类路径?

c - 在C中对文件进行排序

algorithm - 为所有字谜生成相同的唯一哈希码

powershell - 如何使用 Powershell 将哈希表与另一个哈希表进行比较?

java - 我们可以将哈希表写入文件吗?

algorithm - 由两个带指针和值的链表组成的绘图

检查信号是否到达给定的分辨率

C 程序不再在 Ubuntu 中编译

c - 无法将单链表排序为 3 个不同的单链表

c++ - 以下递归程序的最后一行是如何工作的?