首页 > 解决方案 > 值之间的差异以及代码如何读取 CS50 中的值

问题描述

这是我的主要代码:

// Update vote totals given a new vote
bool vote(string name, int candidatecount, candidate candidates1[MAX])
{
    // TODO
    for (int a = 0; a < candidatecount; a++)
    {
        if (candidatecount == a)
        {
            printf("a\n");
            return false;
        }
        if (name == candidates1[a].names)
        {
            printf("b\n");
            candidates[a].votes = candidates[a].votes + 1;
        }
        printf("%s, %s\n", candidates1[a].names, name);
    }
    printf("1\n");
    return(name);
}

这是我的命令行:

    ./plurality R D

输出(我的回答)是这样的:

    Number of voters: 3
    Vote: R
    R, R
    D, R
    1
    Vote: D
    R, D
    D, D
    1
    Vote: R
    R, R
    D, R
    1
    vote candidate 0 go around 0
    b 0 e (null)
    vote candidate 0 go around 1
    b 0 e (null)
    (null) won with 0 votes. 

它使它看起来像这样:

    if (name == candidates1[a].names)

应该工作,但它没有,因为它之后的 printf 不起作用。有谁知道为什么?

标签: cs50string-comparison

解决方案


查看第 3 周的视频,从 40 分钟左右开始。教授说

事实证明,在 C 中,您不能使用 equals 来比较两个字符串。

strcmp当时进行了介绍,并将在下一课中进一步解释原因。简单的解释是字符串是指针,==将比较操作数的地址,而不是


推荐阅读