linked-list - 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 文件中的单词以查看它们是否与链接列表中的任何术语匹配。如果不是,那么它们应该被视为不正确。
解决方案
这if(strcasecmp(cursor->word, word))
是一个问题。从man strcasecmp:
返回值
strcasecmp() 和 strncasecmp() 函数返回一个小于、等于或大于零的整数,如果发现 s1(或其前 n 个字节)分别小于、匹配或大于比s2。
如果单词match,则返回 0,其计算结果为 false。
推荐阅读
- java - 在 Spring Framework 中使用 WebClient 调用 REST 时出错
- python - Python DeDuplicate 对列进行排序并转换为一行
- google-maps - 具有网络链接和数千个多边形的 KML
- c++ - CreateBitmap 图像未在窗口上打印
- typescript - 在没有订阅的情况下将 Observable 结果与现有的 RxJS 主题结合起来
- c# - UI Components not instantiating on Xamarin.IoS on Visual Studio for Mac Community when added from designer
- python - 在 AWS 上的现有 EC2 实例中运行 Python 脚本
- swift - Is this code converting the KUTTypeFileURL as a String, then converting it to a NSPasteboard.PasteboardType?
- .net - 在 VB.NET 中使用本地 X.509 证书 .PFX 解密 XML 文件
- python - Makefile shell 函数和环境变量