Originally Posted by
Salem
In two places, you have short allocated strings which have no \0 termination.
Code:
char *stringletter = malloc(sizeof(char));
scanf("%s", &letter);
*stringletter = letter;
strcspn (used later) needs stringletter to have a \0.
Otherwise, it might match garbage and give you a duff index to write to.
Code:
printf("%s\n", temp);
Again, temp has no \0.
Now I can hear you thinking - "but it works".
Well sure, it "works" for a few iterations of your loop, but you're the one who is here and now all confused as to why your code suddenly blew up.
Thanks for the advice. I tried it out, but now I have a different problem on my hands. Whenever a letter is inputted, when the loop runs again, the program doesn't take in another letter and then it seems the value of the letter variable changes to a value that isn't in the word variable, causing the player to lose a life right after they make an input:
Code:
1You have 5 lives.
-------
Put in a letter.
p
You guessed right.
You have 5 lives.
p------
Put in a letter.
You guessed wrong. You lose a life
You have 4 lives.
p------
Put in a letter.
This is the edited version of the code after I followed your advice:
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;
}
int length = strlen(word);
char *temp = malloc( (length * sizeof(char)) + sizeof(char) );
bool finished = false;
int j;
int lives = 5;
char letter;
char *stringletter = malloc(2*sizeof(char));
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");
scanf("%c", &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];
}
continue;
} 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");
continue;
}
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;
}
Could you please explain why this is happening? The program seems to ignore the scanf command after it prints out "Put in a letter". Thanks for your help.