我是 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
[强调添加]:
返回值
strcmp() 和 strncmp() 函数返回一个小于、等于或大于零的整数,如果发现 s1(或其前 n 个字节)分别小于、匹配或大于比s2。
您可以通过 debug50 获取一个小的定制字典,看看在这一行会发生什么:
if (strcmp(chk->word, word))
由于strcmp
返回 an int
,请像测试一样测试它int
,而不是测试它bool
。而且不要忘记:在检查应区分在敏感!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句