【问题标题】:Cs50 speller: not recognising any incorrect wordsCs50 拼写器:无法识别任何不正确的单词
【发布时间】:2020-05-06 15:38:57
【问题描述】:

我目前正在研究 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-list hashtable cs50


【解决方案1】:

这个if(strcasecmp(cursor-&gt;word, word)) 是个问题。来自man strcasecmp

返回值
strcasecmp() 和 strncasecmp() 函数返回一个 如果 s1(或第一个 n 个字节)分别被发现小于、匹配或 大于 s2。

如果单词匹配,则返回0,结果为false。

【讨论】:

  • 谢谢,这是我的问题。可能对我来说也是一个很好的教训。我认为 1 等于 false,因为当函数返回 1 时,表示程序失败。为我回学校。
猜你喜欢
  • 2014-08-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 2020-09-22
  • 2011-03-06
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多