Search code examples
cif-statementuser-defined-functionsstrcmp

Using strcmp within an if() statement within a user-defined function does not return expected output


I am working on a homework assignment focusing on strings for an Intro to C class. I am having trouble using the strcmp() function within an if statement, within a user-defined function.

The assignment requires us to use a user-defined function (mine is Check()) to check whether two strings are the same (comparing a user-inputted string to a string from a file). For some reason, my professor wants Check() to return a 1 if the strings match and a 2 if the strings don't match, even though to my knowledge strcmp() already returns 0 if the strings match and some other value if they don't.

Once my Check() function returns a value (x=1 for match, x=2 for no match), I run that x value through another if statement within my main function that should print "You are correct" for x=1, and "You are incorrect" for x=2.

The problem I am having is that no matter whether the strings match or not, my conditional within my main function always tells the user they are correct, i.e. the strings match. I assume the issue lies within my Check() function and my use of strcmp(), as I am not entirely familiar with how strcmp() works.

I have already tried modifying my conditional within Check() so that I have if(strcmp(solution, guess)==0) followed by else if(strcmp(solution, guess)!=0), and that did not fix my problem.

My user defined function:

int Check(char solution[], char guess[])
{
   if (strcmp(solution, guess) == 0)
   {
      int x = 1;
      return x;
   }
   else
   {
      int x = 2;
      return x;
   }
}

This is fed to my main function as:

Check(solution, guess);

if (x == 1)
{
   printf("Congratulations, you guessed correctly");
}
else if (x == 2)
{
   printf("You guessed incorrectly");
}

When solution = "FLORIDA" and guess = "FORLIDA", "You guessed incorrectly" should be printed, but "Congratulations, you guessed correctly" is instead.


Solution

  • You are not assigning the return value to any variable.

    Write

    x = Check(solution, guess);
    

    before the if statement.

    if (x == 1)
    {
       printf("Congratulations, you guessed correctly");
    }
    else if (x == 2)
    {
       printf("You guessed incorrectly");
    }
    

    in fact instead of else if you can write just else because there are only two possibilities.

    So without the variable x the if statement may be rewritten like

    if ( Check(solution, guess) == 1 )
    {
       printf("Congratulations, you guessed correctly");
    }
    else
    {
       printf("You guessed incorrectly");
    }
    

    Take into account that the function can be defined simpler

    int Check( const char solution[], const char guess[] )
    {
        return strcmp( solution, guess ) == 0 ? 1 : 2;
    }