I am trying to make a basic text game in C. I am trying to compare a set string with user input but am failing miserably at it. I am rather new to C (I have worked with javascript, php, and C++ in the past). I am sure what I am doing wrong is either blindly simple or is something that I misunderstood when reading documentation.
#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;
}
I ran it through the debugger and your string comparisons are working out fine.
To define a string you can do the following (remember a string is just a pointer to the first character):
char *warrior = "warrior";
char *mage = "mage";
Then...
`if ( strcmp( mage, type ) == 0 ){
//do what you have to do
}
else if ( strcmp (warrior , type ) == 0){
//do what you have to do
}`
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.