Search code examples
cstringstrcmp

strcmp doesn't work in my code


I have a problem with strcmp in my program.
i'm trying to compare two strings by their length, so i'm using strcmp() for that but when i compare them in my if statement it doesn't work well.

Doesn't strcmp compare length of strings?

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

int main(int argc, char *argv[]) {
    char a[30],b[30],c[30];
    strcpy(a,"computer");
    strcpy(c,"science");
    strcpy(b,a);
    puts(a);
    puts(c);
    puts(b);

    if(strcmp(a,b)==0)
        printf("a=b\n");
    if(strcmp(a,c)<0)
        printf("a<c\n");
    if(strcmp(a,c)>0)
        printf("a>c");

    strcat(a,c);
    puts(a);

    getch();
    return 0;
}

Solution

  • strcmp compares strings lexicographically (for strings composed of letters in the same register, it's the same as comparing them alphabetically). Therefore, "computer" is less, not greater, then "science", because it is earlier alphabetically.

    If you would like compare lengths of the two strings rather than comparing the strings themselves, you should use strlen:

    if(strlen(a) == strlen(b))
       printf("a=b\n");
    if(strlen(a) < strlen(c))
       printf("a is shorter than c\n");
    if(strlen(a) > strlen(c))
       printf("a is longer than c");