-5

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'

Idan
  • 227
  • 3
  • 10
  • 2
    the index in C starts from 0. so fromAge[4] doesn't exist. The defined `fromAge[4]` is only from `fromAge[0]` to `fromAge[3]` and so on. – Tom Kuschel Jan 02 '19 at 09:32
  • This isn't how you assign numeric values to a character array. Use atoi() – SPlatten Jan 02 '19 at 09:36

2 Answers2

3

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.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
2

You are checking strings, which means you are checking it alphabetically, and indeed : "2" does not come before "1" in the alphabet: in ASCII, the value for "2" is 50, while the value for "1" is 49, and indeed: 50 does not come before 49.

Therefore it's always a bad idea to use numbers a strings, just treat them as numbers and everything should be fine:

int FromAge;
int ToAge;
...

Good luck

Dominique
  • 16,450
  • 15
  • 56
  • 112