Search code examples
cstrcmp

STRCMP on numeric strings


so I have 3 variables:

char fromAge[4];
char toAge[4];
char age[4];

They can all have a number between 18 and 100 (include 18 and 100). When I give them the follwing values, the following statement is wrong for some reason:

fromAge[4] = 18;
toAge[4] = 100;
age[4] = 25;
if (strcmp(age, fromAge) >= 0 && strcmp(age, toAge) <= 0)
{
//actions
}

It thinks "age" isn't smaller or equals to "toAge". Any suggestions for why?

edit: This is how I assign the variables, I leave 1 byte for '\0'

scanf("%s", fromAge);
scanf("%s", toAge);

and age is 2,5,'\0'


Solution

  • strcmp compares strings by comparing the individual characters from left to right and it will return as soon as two characters differ. As the character '1' is less than the character '2', the string "100" will be considered less than the string "25".

    Try this code and give the input "100" and "25"

    int main()
    {
      char toAge[4] = {0};
      char age[4]={0};
      scanf("%3s", age);
      scanf("%3s", toAge);
    
      // Using string compare
      if (strcmp(age, toAge) < 0)
        printf("\"%s\" is less than \"%s\"\n", age, toAge);
      else if (strcmp(age, toAge) > 0)
        printf("\"%s\" is greater than \"%s\"\n", age, toAge);
      else
        printf("\"%s\" is equal to \"%s\"\n", age, toAge);
    
      // Using integer compare
      if (atoi(age) < atoi(toAge))
        printf("%s is less than %s\n", age, toAge);
      else if (atoi(age) > atoi(toAge))
        printf("%s is greater than %s\n", age, toAge);
      else
        printf("%s is equal to %s\n", age, toAge);
    
      return 0;
    }
    

    Output:

    "100" is less than "25"
    100 is greater than 25
    

    As you can see the function atoi can be used to get the result you expect.