In my code for a hangman game below, the lives variable suddenly changes its value from 5 to 0 during runtime:
Code:
You have 5 lives.
-------
Put in a letter.
p
You guessed right.
You have 0 lives.
p------
Put in a letter.
Below is my code:
Code:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char *word;
int i = rand() % 2;
printf("%d", i);
switch(i) {
case 0:
word = "string";
break;
case 1:
word = "program";
break;
}
char *placeholder = word;
int length = strlen(word);
char *temp = malloc( length * sizeof(char) );
bool finished = false;
int j;
int lives = 5;
for(j=0; j<(length); j++) {
temp[j] = '-';
}
lives = 5;
while(finished == false) {
printf("You have %d lives.\n", lives);
printf("%s\n", temp);
printf("Put in a letter.\n");
char letter;
char *stringletter = malloc(sizeof(char));
scanf("%s", &letter);
*stringletter = letter;
if( (strrchr(word, letter) != NULL) && (strrchr(temp,letter) == NULL) ) {
int index = strcspn(word, stringletter);
printf("You guessed right.\n");
temp[index] = letter;
for(j=0; j<length; j++) {
if(word[j] == letter)
temp[j] = word[j];
}
} else if(strrchr(word, letter) == NULL) {
printf("You guessed wrong. You lose a life\n");
--lives;
} else {
printf("You already have that letter. Try again.\n");
}
if(strcmp(word, temp) == 0) {
printf("You win! You guessed the word correctly. It's %s\n", word);
break;
}
if(lives < 0) {
printf("You're out of lives. You lose.\n");
break;
}
}
return 0;
}
I am unsure why this is happening. Could someone help me find out why?