Search code examples
cif-statementstrcmpc-strings

If statement in C always returning false


I am fairly new to C, so am not overly familiar with it's syntax, however I have debugged my code and researched for the correct syntax, and it seems to be correct, I have also changed the scope of the variables to see if this was causing the error.

The if statement should compare two variables, which both hold strings, I have even printed both the variables out to ensure they are the same, however it is still skipping straight to the else section of the if statement. Can anyone give me any pointers on why it will not run the if statement, it just skips straight to 'incorrect'.

The correctWord variable is defined at a different section in the code.

Find full code here.

-UPDATE-

I have now updated the syntax of the code, however it is still returning false.

Output screen

char correctWord[20];

void userGuess(){
    char userWordGuess[20];

    printf("Anagram: ");
    printf(anagramWord);
    printf("Your Guess: ");
    scanf("%s",userWordGuess); //Reads in user input

    printf(correctWord);
    printf(userWordGuess);

    if(strcmp(userWordGuess, correctWord) == 0){
        printf("Congratulations, you guessed correctly!");
    }else{
        printf("Incorrect, try again or skip this question");
    }
}

Solution

  • You cannot compare strings in C using ==, because this compares the addresses of the strings, not the contents of the string. (which you certainly don't require, and obviously, the addresses of the two strings are not equal too.)

    C has a pretty nice function for it : strcmp() which returns 0 if both the strings are equal.

    Try using this in your if condition:

    if (!strcmp(userWordGuess,correctWord))
    {
         //Yay! Strings are equal. Do what you want to here.
    }
    

    Be sure to #include <string.h> before using strcmp().