CS50 Pset5 check() 将太多单词视为拼写错误

标签 c trie cs50

我已将字典加载到树结构中,并成功获得了peller.c,并使用以下 load() 和 check() 实现进行编译。

但是,当我运行该程序时,我的 check() 函数将不正确的单词数计为拼写错误。 (对于 lalaland.txt,它是 17756 个单词中的 17187 个)。

我无法弄清楚我的代码出了什么问题,并且非常感谢任何可以帮助我指出正确方向的人。

typedef struct node
{
  bool isword;
  struct node *children[27];
}
node;
node *root = NULL;

// Function returns the position of any given letter in the alphabet e.g. a = 1, b = 2 etc. Returns 0 for an apostrophe.
int index(char letter)
{
    if (isalpha(letter))
    {
        int i = letter - 96;
        return i;
    }

    return 0;
}


// Keeps track of number of words loaded into dictionary.
unsigned int wordno = 0;

// Returns true if word is in dictionary else false
bool check(const char *word)
{

    char newword[LENGTH + 1];
    node *temp = root;

    for (int j = 0; j < strlen(word); j++)
    {
        //Makes each letter of the input lowercase and inserts it into a new array.
         newword[j] = tolower(word[j]);
    }

    for (int i = 0; i < strlen(word); i++)
    {
        //Finds the position of the character in the alphabet by making a call to index().
        int letter = index(newword[i]);

        if (temp->children[letter] == NULL)
        {
            return false;
        }

        else
        {
           temp = temp->children[letter];
        }

    }

    if (temp->isword == true)
    {
        return true;
    }

     return false;

}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
  FILE *dict = fopen(dictionary, "r");

  root = calloc(1, sizeof(node));
  node *temp = root;

  if (dict == NULL)
  {
    fprintf(stderr, "Could not load dictionary.\n");
    return false;
  }

  char word[LENGTH+1];


  while (fscanf(dict, "%s", word) != EOF)
  {

    for (int i = 0; i < strlen(word); i++)
    {
        int letter = index(word[i]);

        if (temp->children[letter] == NULL)
        {
            temp->children[letter] = calloc(1, sizeof(node));

            if ((temp->children[letter]) == NULL)
            {
                unload();
                return false;
            }
        }
        temp = temp->children[letter];

    }

    temp->isword = true;
    wordno++;


   }

  return true;

}

最佳答案

node *temp = root;

应该放置在这个 while 循环内:

while (fscanf(dict, "%s", word) != EOF)

通过这样做,每次循环开始迭代文件中的新单词时,您都可以让 temp 返回并指向根节点。

关于CS50 Pset5 check() 将太多单词视为拼写错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51664890/

相关文章:

c++ - C 中按 "a A b B c C"顺序对字符串数组进行排序

cs50 pset1 贪婪。我不必使用%?

CS50 IDE clang : error: linker command failed with exit code 1

c - 调用函数时出现 'expected expression'错误如何解决?

c++ - 在 C/C++ 中进行数学运算时,我应该对哪些变量进行类型转换?

c - 将数据附加到字符数组中的空字符以通过套接字发送数据

c - 环形缓冲区困难

algorithm - 用于存储由唯一的 8 位十六进制标识的对象的数据结构,用于快速插入和查找

c# - 在 C# 中,搜索列表中的元素但执行 "StartsWith()"搜索的最快方法是什么?

c - 层次树打印所有后缀提供错误的输出