strcmp 对 2 个相同字符串的行为不当

strcmp misbehave with 2 same strings

我有这个代码:

#include <stdio.h>
#include <string.h>

int main() {

  char s1[50], s2[50];

  printf("write s1:\n");
  fgets(s1, sizeof(s1), stdin);

  printf("s2:\n");
  fgets(s2, sizeof(s2), stdin);

  printf("The concatenation of the two strings: %s\n", strcat(s1, s2));

  if( strcmp(s2, s1) < 0 ) {
    printf("s2 is shorter than s1.\n");
  } else if( strcmp(s2, s1) > 0 ) {
    printf("s2 is longer than s1.\n");
  } else {
    printf("strings are equal.\n");
  }

  return 0;
}

问题是,当我写 2 个相同的字符串(如 abc 或其他)时,strcmp return "s2 is shorter than s1."

这是正常输出还是我做错了什么?如果有,在哪里?

或者strcat让字符串不相等?对此有什么办法吗?

谢谢

你在做

 strcat(s1, s2)

比较之前。这将修改字符串 s1 因此字符串将不相等

您在执行 strcmp 之前先执行 strcat。 strcat 会将 s2 连接到 s1

Strcmp 根据内容的值(类似于字典顺序,如果你愿意,但不完全是那样)而不是根据它们的长度来比较字符串。

例如:"abc" > "abb"

尝试替换

    printf("The concatenation of the two strings: %s\n", strcat(s1, s2));

    printf("The two strings are: '%s' and '%s' and their concatenation: '%s'\n",
    s1, s2, strcat(s1, s2));

然后阅读 strcat 的描述。

如果这没有帮助,请将 %s 序列替换为 %p。 (可能您必须阅读 printf 文档中对 %p 格式说明符的描述。)