我正在尝试用 C 语言制作一个基本的文本游戏。我正在尝试将一组字符串与用户输入进行比较,但失败得很惨。我对 C 相当陌生(我过去曾使用过 javascript、php 和 C++)。我确信我做错的事情要么是盲目简单,要么是我在阅读文档时误解的。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main(void) {
/* Game variables */
bool game_over = false,
is_mage = false,
is_warrior = false;
unsigned int sword_damage = 15,
magic_damage = 10,
magika = 20,
strength = 20,
health = 100,
gold = 20;
char name [20],
type [7],
dest_1 [7],
dest_2 [7],
mage [4],
warrior[7];
/* Make string variables */
memset(dest_1, '\0', sizeof(dest_1));
memset(dest_2, '\0', sizeof(dest_2));
strcpy(mage, "mage");
strcpy(dest_1, mage);
strcpy(warrior, "warrior");
strcpy(dest_2, warrior);
/* Print introduction and set up player */
printf("\t\t\t\tAngrokk\n\t\tCopyright: Benjamin Williams 2013\n\n");
printf("Character name: ");
scanf("%s",name);
printf("\nCharacter type (mage/warrior): ");
scanf("%s",type);
if (strcmp(type, dest_1) == 0) {
is_mage = true;
} else if (strcmp(type, dest_2) == 0) {
is_warrior = true;
} else {
printf("No type available, game shutting down.");
return 0;
}
/* Main game loop */
while (!game_over) {
/* Detect if the character is dead or not */
if (health < 0) {
game_over = true;
}
}
printf("Game over");
return 0;
}
最佳答案
我通过调试器运行了它,并且您的字符串比较运行良好。
要定义字符串,您可以执行以下操作(记住字符串只是指向第一个字符的指针):
char *warrior = "战士";
char *mage = "法师";
然后...
`if ( strcmp( 法师,类型 ) == 0 ){
//做你必须做的事情
}
else if ( strcmp (战士, 类型) == 0){
//做你必须做的事情
}`
关于与 C 比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20026772/