This is a very fun problem I am running into. I did a lot of searching on stack overflow and found others had some similar problems. So I wrote my code accordingly. I originally had fscan()
and strcmp()
, but that completely bombed on me. So other posts suggested fgets()
and strncmp()
and using the length to compare them.
I tried to debug what I was doing by printing out the size of my two strings. I thought, maybe they have /n
floating in there or something and messing it up (another post talked about that, but I don't think that is happening here). So if the size is the same, the limit for strncmp()
should be the same. Right? Just to make sure they are supposedly being compared right. Now, I know that if the strings are the same, it returns 0
otherwise a negative with strncmp()
. But it's not working.
Here is the output I am getting:
perk
repk
Enter your guess: perk
Word size: 8 and Guess size: 8
Your guess is wrong
Enter your guess:
Here is my code:
void guess(char *word, char *jumbleWord)
{
size_t wordLen = strlen(word);
size_t guessLen;
printf("word is: %s\n",word);
printf("jumble is: %s\n", jumbleWord);
char *guess = malloc(sizeof(char) * (MAX_WORD_LENGTH + 1));
do
{
printf("Enter your guess: ");
fgets(guess, MAX_WORD_LENGTH, stdin);
printf("\nword: -%s- and guess: -%s-", word, guess);
guessLen = strlen(guess);
//int size1 = strlen(word);
//int size2 = strlen(guess);
//printf("Word size: %d and Guess size: %d\n",size1,size2);
if(strncmp(guess,word,wordLen) == 0)
{
printf("Your guess is correct\n");
break;
}
}while(1);
}
I updated it from suggestions below. Especially after learning the difference between char *
as a pointer and referring to something as a string. However, it's still giving me the same error.
Please note that MAX_WORD_LENGTH
is a define statement used at the top of my program as
#define MAX_WORD_LENGTH 25