c - 如何与 If 两个字符串的值进行比较?
问题描述
我想比较两个字符串并显示每个玩家的获胜次数。我不太明白 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++;
}
推荐阅读
- algorithm - 使用反向替换计算算法的复杂度
- blazor - 将 EditFrom 拆分为多个组件
- node.js - 如何在 AWS sdk nodejs 中更改 aws 配置文件
- google-cloud-platform - 在 GCP cloudbuild.yaml 中指定与“名称”不同的“执行函数”
- javascript - JavaScript add 和 removeEventListeners 带参数的回调
- gitlab - 未能加载代码气候报告,但报告存在
- python - 开始使用 mypy / 忽略外部库
- python - Python Selenium - 如何单击非按钮元素
- c# - C# 只允许一个类调用不同类的属性设置器(或者让类知道它是否存储在另一个类的数组中)
- javascript - 遍历 ID 数组并修改相应的元素