【问题标题】:strcmp returns 1 when 2 strings are equal, Why?当 2 个字符串相等时,strcmp 返回 1,为什么?
【发布时间】:2014-11-17 04:17:44
【问题描述】:

我有以下代码。我从http://www.gnu.org/software/libc/manual/html_node/crypt.html 拿的

#define _XOPEN_SOURCE
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <crypt.h>

int
main(void)
{
  /* Hashed form of "GNU libc manual". */
  const char *const pass = "$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/";

  char *result;
  int ok;

  printf("%s\n",pass);

  /* Read in the user’s password and encrypt it,                                                                                                    
     passing the expected password in as the salt. */
  result = crypt(getpass("Password:"), pass);

  printf("%s\n",result); /*I added this printf*/
  /* Test the result. */
  ok = strcmp (result, pass) == 0;
  printf("valor de la comparacion: %i\n",ok);/*I added it*/
  puts(ok ? "Access granted." : "Access denied.");
  return ok ? 0 : 1;
}

当我输入 GNU libc 手册时,输出是“授予访问权限”。但是strcmp返回的值是1,这个值意味着result和pass不相等。但是输出是:

$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/
Password:
$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/
valor de la comparacion: 1
Access granted.

我对 strcmp 的行为感到非常困惑。

【问题讨论】:

  • 我认为正在检查条件strcmp (result, pass) == 0,因为这个条件为真,这就是它返回1的原因。尝试在printf 中打印strcmp (result, pass)
  • 如果两个字符串具有相同的内容,我希望 strcmp (result, pass) == 0 返回一个非零数字。
  • @bvj 如果两个字符串的内容相同,它将返回 0。
  • @Himanshu "It" 是 strcmp,正确。那么就我而言,0==0 会如何评估?
  • @bvj 0==0 表示条件为真(因为零等于零),所以它将返回1

标签: c string strcmp


【解决方案1】:

您正在打印ok 的值。

在这一行:

ok = strcmp (result, pass) == 0;

它将strcmp 的返回值与0 进行比较。它们是相等的,所以比较是正确的。这会将ok 设置为1。将整数设置为布尔比较的结果,1 为真,0 为假。

【讨论】:

  • 和小整改是——删除== 0 :)
  • 没错。我错了,这是 strcmp(result,pass) == 0 的值。它不是 strcmp 本身返回的值
  • 正如remyabel 刚刚指出的那样,那行代码取决于=,其运算符优先级低于==
【解决方案2】:

赋值运算符= 的优先级低于关系运算符==。所以声明ok = strcmp (result, pass) == 0; 等价于ok = (strcmp (result, pass) == 0);。您不是strcmp 的结果分配给ok,而是将strcmp (result, pass) == 0 的结果分配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多