Reputation: 794
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
Upvotes: 0
Views: 237
Reputation: 9570
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.)
Upvotes: 1
Reputation: 8819
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"
Upvotes: 1
Reputation: 1000
you are doing a strcat before doing doing strcmp. strcat would concatenate s2 to s1
Upvotes: 1
Reputation: 19864
You are doing
strcat(s1, s2)
before comparing. Which will modify string s1
so strings will not be equal
Upvotes: 4