用C比较字符串

时间:2013-11-17 03:16:00

标签: c string compare

我正在尝试用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;
}

1 个答案:

答案 0 :(得分:0)

我通过调试器运行它,你的字符串比较工作正常。

要定义字符串,您可以执行以下操作(请记住字符串只是指向第一个字符的指针):

char * warrior =“warrior”;

char * mage =“mage”;

则...

`if(strcmp(mage,type)== 0){

//做你必须做的事

}

else if(strcmp(warrior,type)== 0){

//做你必须做的事

}`

相关问题