Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is fgets() and strncmp() not working in this C code for string comparison?
    primarykey
    data
    text
    <p>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 <code>fscan()</code> and <code>strcmp()</code>, but that completely bombed on me. So other posts suggested <code>fgets()</code> and <code>strncmp()</code> and using the length to compare them. </p> <p>I tried to debug what I was doing by printing out the size of my two strings. I thought, maybe they have <code>/n</code> 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 <code>strncmp()</code> 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 <code>0</code> otherwise a negative with <code>strncmp()</code>. But it's not working. </p> <p>Here is the output I am getting: </p> <pre><code>perk repk Enter your guess: perk Word size: 8 and Guess size: 8 Your guess is wrong Enter your guess: </code></pre> <p>Here is my code:</p> <pre><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); } </code></pre> <p>I updated it from suggestions below. Especially after learning the difference between <code>char *</code> as a pointer and referring to something as a <em>string</em>. However, it's still giving me the same error. </p> <p>Please note that <code>MAX_WORD_LENGTH</code> is a define statement used at the top of my program as </p> <pre><code>#define MAX_WORD_LENGTH 25 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload