c - 当 2 个字符串相等时,strcmp 返回 1,为什么?

标签 c string strcmp

我有以下代码。我从 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 manual 时,输出为“已授予访问权限”。但是 strcmp 返回的值为 1,这个值意味着 result 和 pass 不相等。但是输出是:

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

我对 strcmp 的行为很困惑。

最佳答案

您正在打印 ok 的值。

在这一行:

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

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

关于c - 当 2 个字符串相等时,strcmp 返回 1,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26965447/

相关文章:

c - 在系统函数中调用 OpenCV 捕获代码时卡住

java - 尝试将 zip 文件内容的字符串表示形式保存为 Java 中的文件

Python-仅在字符串的开头查找字符串

c - "series"中的 strcmp()

c - strcmp 在进行套接字 I/O 时不工作

c - 如何在 EOF 之前读取无限字符串并将它们放入 C 中的 char 数组?

c - 如何将两个不等数组的每个元素相加并将其存储在第三个数组中?

php - C 和 PHP 之间 if ('0' ) 的内部差异?

python - 从python中的列表中获取第一个非空字符串

c - strcmp() 来自标准输入的字符串和来自文件的字符串