I'm currently working my way through CS50x and just tinkering around with some of the practice problems from Week 1 and testing the limits of my knowledge. Could someone help me understand why the two strings "my_month" and "your_month" aren't equal?
I've tested it and if I print the string for "my_month" it prints "October" - but if I enter "October" for "your_month" it doesn't seem to think that it is equivalent to the string in the array.
string month [] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
string my_month = month [9];
string your_month = get_string("What month were you born? ");
if (your_month == my_month)
{
printf("%s\n", your_month);
}
The reason is because technically they aren't equal. When you use '==' on strings, what you are comparing is their addresses.
To compare the contents of 2 string you have you have to use strcmp().
So your code should look like this:
if (strcmp(your_month, my_month) == 0)
{
printf("%s\n", your_month);
}
strcmp()
works by comparing each character's ASCII value. So it can also tell you if the first string is "more" or "less" than the second one.
For example:
strcmp("lol", "LOL");
Will return a value bigger than 0 which means the ASCII values of "lol" are higher than those of "LOL"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments