在用户定义函数的 if() 语句中使用 strcmp 不会 return 预期输出

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

我正在做一项家庭作业,重点是 C 入门的字符串 class。我在用户定义函数的 if 语句中使用 strcmp() 函数时遇到问题。

作业要求我们使用用户定义的函数(我的是Check())来检查两个字符串是否相同(将用户输入的字符串与文件中的字符串进行比较)。出于某种原因,我的教授希望 Check() return 如果字符串匹配则为 1,如果字符串不匹配则为 2,即使据我所知 strcmp() 已经 returns 0 如果字符串匹配,如果不匹配则为其他值。

一旦我的 Check() 函数 return 有一个值(x=1 表示匹配,x=2 表示不匹配),我 运行 通过主函数中的另一个 if 语句得到 x 值应该为 x=1 打印 "You are correct",为 x=2 打印 "You are incorrect"。

我遇到的问题是,无论字符串是否匹配,我在 main 函数中的条件总是告诉用户它们是正确的,即字符串匹配。我认为问题在于我的 Check() 函数和我对 strcmp() 的使用,因为我并不完全熟悉 strcmp() 的工作原理。

我已经尝试在 Check() 中修改我的条件,以便我有 if(strcmp(solution, guess)==0) 后跟 else if(strcmp(solution, guess)!=0),然后没有解决我的问题。

我的用户定义函数:

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

这是我的主要功能:

Check(solution, guess);

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

当 solution = "FLORIDA" 和 guess = "FORLIDA" 时,应该打印 "You guessed incorrectly",但 "Congratulations, you guessed correctly" 是。

您没有将 return 值分配给任何变量。

x = Check(solution, guess);

在 if 语句之前。

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

事实上,您可以只写 else 而不是 else if,因为只有两种可能性。

所以如果没有变量 x if 语句可以重写为

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

考虑到函数可以定义得更简单

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