首页 > 解决方案 > Cs50 拼写器:无法识别任何不正确的单词

问题描述

我目前正在研究 CS50 Speller 功能。我已经设法编译了我的代码并完成了完整程序的原型,但是它不起作用(它无法识别任何拼写错误的单词)。我一次一个地浏览我的函数并打印出它们的输出来看看里面发生了什么。

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

据我所知,这很好用。这让我想知道问题是否与我的检查功能有关,如下所示:

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

如果有更敏锐的眼睛的人可以窥探是什么问题,我会非常感激,因为我很难过。第一个函数用于将字典中的单词加载到哈希表\链表中。第二个函数应该检查 txt 文件中的单词以查看它们是否与链接列表中的任何术语匹配。如果不是,那么它们应该被视为不正确。

标签: linked-listhashtablecs50

解决方案


if(strcasecmp(cursor->word, word))是一个问题。从man strcasecmp

返回值
strcasecmp() 和 strncasecmp() 函数返回一个小于、等于或大于零的整数,如果发现 s1(或其前 n 个字节)分别小于、匹配或大于比s2。

如果单词match,则返回 0,其计算结果为 false。


推荐阅读