Reputation: 33
Hello i am creating hangman game and i have function which check if a word is guessed
Input parameters is secret "computer" for example and letters_guessed is which letters have been already guessed for example "fgtcsomputdser"
if computer can be built from these letters returns 1
my function wont work because if i try to run it for secret = computer and guessed = comp it returns me 1 word is guessed
int is_word_guessed(const char secret[], const char letters_guessed[]) {
int guessed;
for(int i = 0; i < strlen(secret); i++) {
guessed = 0;
for(int j = 0; j < strlen(letters_guessed); j++) {
if(secret[i] == letters_guessed[j]) {
guessed = 1;
break;
}
}
}
if(guessed) return 1;
else return 0;
}
Upvotes: 0
Views: 693
Reputation: 180998
You are checking for each letter in secret
whether that letter is also in letters_guessed[]
, but you do not retain the result for one letter when you proceed to check the next. Therefore, the final result tells you only about the last letter checked, not the whole word.
There are various ways around this, but I suggest reversing the sense of your test: look for any letter in secret
that is not in letters_guessed
. Return 0 as soon as you find such an unguessed letter, or return 1 if the loop terminates without finding one.
Upvotes: 1
Reputation: 5220
You could count the number of guessed letters from the secret, and if that number is the same as the length of the secret, then the word was guessed
int is_word_guessed(const char secret[], const char letters_guessed[]) {
int guessed = 0;
for(int i = 0; i < strlen(secret); i++) {
for(int j = 0; j < strlen(letters_guessed); j++) {
if(secret[i] == letters_guessed[j]) {
guessed ++;
break;
}
}
}
if(guessed == strlen(secret)) return 1;
else return 0;
}
Upvotes: 1