简体   繁体   中英

strcmp misbehave with 2 same strings

I have this code:

#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;
}

The problem is that when I write 2 same strings like abc or whatever, strcmp return "s2 is shorter than s1."

Is that the normal output or have I done anything wrong? If so, where?

Or strcat makes the string not equal? Can anything be done about this?

Thank you

You are doing

 strcat(s1, s2)

before comparing. Which will modify string s1 so strings will not be equal

you are doing a strcat before doing doing strcmp. strcat would concatenate s2 to s1

Strcmp compares the strings according to the value of their contents (similar to the dictionary order, if you like, but not exactly that) not according to their length.

For example: "abc" > "abb"

Try replacing

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

with

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

Then read a description of strcat .

If that doesn't help, replace %s sequences with %p . (Possibly you'll have to read a description of the %p format specifier in the printf documentation.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM