c - Bool 函数在不满足条件的情况下返回 true - 忽略 printf()

标签 c return boolean printf conditional-statements

我已经在这个程序上连续工作了 5 天,但不明白为什么它会这样。谢谢你帮我。

文件speller.c中有代码调用了文件dictionary.c中的4个函数
在speller.c中,它调用了某个函数:

bool misspelled = !check(word);

如果 misspelled 为 false,则表示检查函数返回 true。

这是 dictionary.c 中的检查函数:

bool check(const char *word)
{
    int key = hash(word);
    printf("Word: %s    position: %i\n", word, key);
    node* trav = dictArray[key];

    while (trav != NULL)
    {
        if(trav->word == word)
            printf("%s found in the dictionary\n", word);
            return true;
        trav = trav->next;
    }
    printf("%s NOT found in the dictionary\n", word);
    return false;

Check() 如果可以在哈希表中找到作为参数传递的单词,它将检查哈希表,并打印每个单词及其键。如果找到它,它会打印一条消息并返回 true。如果不是,则打印一条消息,并返回 false。 哈希表是一个包含 26 个元素的数组,每个元素都是一个包含 2 个元素的结构,一个是字符串,另一个是指向列表中下一个结构(节点)的指针。 根据单词的第一个字母将节点添加到列表中。

问题是我已经测试了添加到数组中的每个单词,即使单词不存在,函数仍然返回 true。 事实上,对于作为参数传递的每个单词,它都会返回 true

现在真正令人费解的行为是 check() 必须在返回 truefalse 之前向屏幕打印一些内容。 ...found ...... NOT found ...。 好吧,事实并非如此。但它仍然返回“真”,这让我很困惑。

有什么帮助吗? 我应该从两个文件中粘贴整个代码吗?

最佳答案

仔细观察:

while (trav != NULL)
{
    if(trav->word == word)
        printf("%s found in the dictionary\n", word);
        return true;
    trav = trav->next;
}

if block 周围没有大括号。因此,通过适当的缩进,您真正拥有的是:

while (trav != NULL)
{
    if(trav->word == word)
        printf("%s found in the dictionary\n", word);
    return true;
    trav = trav->next;
}

所以你总是在第一次循环迭代时返回 true。

此外,您不想使用 == 来比较字符串。您最终要做的是比较指针值,这几乎总是不相等的。使用 strcmp 来比较字符串。

固定代码:

while (trav != NULL)
{
    if(!strcmp(trav->word, word)) {
        printf("%s found in the dictionary\n", word);
        return true;
    }
    trav = trav->next;
}

关于c - Bool 函数在不满足条件的情况下返回 true - 忽略 printf(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52068727/

相关文章:

c - char数据类型在32位寄存器中是如何表示的?

python - return True/False 实际上做了什么? (Python)

C# - 返回后在 catch block 中重新抛出异常

C# 窗体,属性不起作用?

sql - 在 Select 中将 boolean 值返回为 TRUE 或 FALSE (PostgreSQL/pgAdmin)

函数可以返回字符串作为其输出吗?

c - 解码后的shellcode不执行: Illegal instruction: 4

c - 了解有关字节序的 C 代码

c++ - 我的函数的返回结果是打印到控制台,只有在我称之为 C++ 时它才会工作

python - 真值评估无效时是否存在任何内置 Python 值?