c - 如何比较两个字符串的If值?

标签 c

我想比较两个字符串并显示每个玩家的获胜次数。我不太明白 string.h 库是如何工作的,但在搜索中我已经表明它应该适用于这种比较

#include <stdio.h>
#include <string.h>

int main()
{
    printf("Player 1: ");
    scanf("%s", &play1);
    printf("Player 2: ");
    scanf("%s", &play2);            
    printf("Total matches: ");
    scanf("%d", &t_matches);

    for (i = 1; i <= t_matches; i++) {
        printf("Winner match %d: ", i);
        scanf("%s", &win1);
        if (strcmp(win1, play1)) {
            p1++; 
        } else if(strcmp (win1, play2)) {
            p2++; 
        }
    }
    printf("%s win %d matches\n", play1, p1);
    printf("%s win %d matches\n", play2, p2);
}

最佳答案

如果字符串相等,strcmp 函数将返回 0。您正在检查它们是否不平等。相反,您想要:

if (strcmp(win1, play1) == 0) {
    p1++; 
} else if(strcmp (win1, play2) == 0) {
    p2++;
}

关于c - 如何比较两个字符串的If值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55682056/

相关文章:

c - K&R C 练习 4-9 : Why ignore EOF?

在c中将浮点csv转换为二维数组

c - copy_from_user是否修改用户指针?

c++ - 为多边形轮廓绘制圆的最有效方法

c - 如何将字符串从文件传递到链表

c - C 中的 long long 乘法给出错误的结果

c - 链表C编程错误插入新元素

c - 为什么清除变量后会丢失数据

将 char 数组的内容复制到另一个

c - C 中的静态内存分配