Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why aren't these two strings equivalent? C

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);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading