user5983028
user5983028

Reputation:

If statements in my C code are doing the exact opposite of the conditions?

So i'm comparing two strings and my code is doing the exact opposite of what it should be doing. I can't switch up my printf statements because then that would also be wrong. If i input the first string that has length 5 and a second string with length 6, it will say that string 1 is GREATER than string 2 when it's the exact opposite.
Here is what I have:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
    char str1[100], str2[100];

      printf("enter the first string :");
      scanf("%s", &str1);
      printf("enter the second string :");
      scanf("%s", &str2);

     if(strcmp(str1,str2)==0){
        printf("the strings are equal\n");
     }
     else if(strcmp(str1,str2)<0){ 
        printf("string 1 is less than string 2\n");
     }
     else{
        printf("string 1 is greater than string 2\n");
     }
    return 0;
}

Upvotes: 0

Views: 103

Answers (2)

Sunny Onesotrue
Sunny Onesotrue

Reputation: 152

Strcmp compares the strings according to the alphabetical order. To compare the length of the strings, just replace strcmp() with strlen().

Upvotes: 0

gnasher729
gnasher729

Reputation: 52538

strcmp doesn't compare the lengths of strings. It compares characters until it founds two that are not the same, then returns a negative or positive number depending on which string had the character earlier in the alphabet. If one string runs out ("Hello" vs. "Hell") then the shorter one comes first. And if they are identical then the result is 0.

For example, "xyz" > "abcde" because x comes after a.

Upvotes: 1

Related Questions