0

I need to create this program in C and before i accepted simply an ID and compared the ID in the List with the given ID, which worked fine. However, i need to compare the name of a city instead of the id. How does that work in C?

Old code:

// Finds a city in a given CityList with an integer id.
City *findCity(CityList *cl, int id)
{
    int i;


   
    City *s = NULL;


    for (i = 0; i < cl->count; i++)
        if (cl->city[i]->cityId == id))
        {
 
            s = cl->city[i];
        }

    return s;
}

So this worked just fine, however, i need to find a city by using an string (char *) to check if its in the list. Any ideas?

My approach:

City *findCity(CityList *cl, char *name)
{
    int i;


   
    City *s = NULL;


    for (i = 0; i < cl->count; i++)
        if (cl->city[i]->cityId == name))
        {
 
            s = cl->city[i];
        }

    return s;
}

Which isn't working as i saw that you can't use == in C.

Prometheus
  • 799
  • 8
  • 28
  • 5
    Of course you can use `==` in C. But you need to use `strcmp` and friends if you want to compare the contents of 2 NUL terminated `const char` arrays. – Bathsheba Dec 22 '20 at 14:11
  • 2
    Does this answer your question? [How do I properly compare strings in C?](https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c) – Krishna Kanth Yenumula Dec 22 '20 at 14:13
  • Got it. I tried strcmp before and tried to check if its 0, however, i could just make it inside my if statement. – Prometheus Dec 22 '20 at 14:38

0 Answers0