简单的石头剪刀布游戏,它比较两个玩家的选择并决定谁是赢家或是否是平局
1、输入问题:你使用scanf("%s %s",ch1,ch2);来获取两个字符串。这可能会导致缓冲区溢出,因为%s会在遇到空格或换行符时停止读取。为了更安全地读取字符串,建议使用fgets。
2、比较问题:你使用==来比较字符串,这在C中并不安全。应该使用strcmp函数来比较字符串。
3、打印玩家问题:你使用printf("Player1\n");和printf("Player2\n");来打印赢家。然而,由于你的输入和比较逻辑,这两个打印语句可能不会正确地标识赢家。#include <stdio.h>
#include <string.h>
int main() {
int n;
scanf("%d", &n);
getchar(); // consume newline left-over from previous input
char ch1[9], ch2[9];
for (int a = 0; a < n; a++) {
fgets(ch1, sizeof(ch1), stdin); // read input safely
fgets(ch2, sizeof(ch2), stdin); // read input safely
// Remove newline character from fgets reads
ch1[strcspn(ch1, "\n")] = 0;
ch2[strcspn(ch2, "\n")] = 0;
if (strcmp(ch1, "Rock") == 0 && strcmp(ch2, "Scissors") == 0) {
printf("Player1\n");
} else if (strcmp(ch1, "Scissors") == 0 && strcmp(ch2, "Paper") == 0) {
printf("Player1\n");
} else if (strcmp(ch1, "Paper") == 0 && strcmp(ch2, "Rock") == 0) {
printf("Player1\n");
} else if (strcmp(ch2, "Rock") == 0 && strcmp(ch1, "Scissors") == 0) {
printf("Player2\n");
} else if (strcmp(ch2, "Scissors") == 0 && strcmp(ch1, "Paper") == 0) {
printf("Player2\n");
} else if (strcmp(ch2, "Paper") == 0 && strcmp(ch1, "Rock") == 0) {
printf("Player2\n");
} else if (strcmp(ch1, ch2) == 0) {
printf("Tie\n");
} else {
printf("Invalid input! Both should be Rock, Scissors or Paper.\n");
}
}
return 0;
}
|