-1

I am trying to compare strings that I have gotten from a struct Array and am trying to see if both are equal before I print it out.

        int index;

        for (int i = 0; strlen((cityArr+i)->cityname) != 0; i++) {
            for (int j = 0; strlen((cityArr+j)->cityname) != 0; j++) {
                if (strcmp(cityArr[i].cityname, cityArr[j].cityname) == 0) {
                    index = i;
                }
            }
        }

        printf("%s\n", cityArr[index].cityname);

So the information I have basically means that I should just print a duplicate right?

However, my output is: San Jose Fort Worth San Diego Pittsburgh Omaha Stockton Austin New York Corpus Christi Fort Worth

I believe that the only city that should be printed is Fort Worth, not all the cities (which is the case here).

Someone identified my question as a duplicate - I read through the topic, but I somewhat understand how does strcmp work. strcmp is returns a value of 0 if the strings are equal, but here I am trying to print out the equal city names, but instead it prints out every city in the array I am working on.

  • Possible duplicate of [Why does strcmp() return 0 when its inputs are equal?](https://stackoverflow.com/questions/595450/why-does-strcmp-return-0-when-its-inputs-are-equal) – jotaelesalinas Nov 22 '18 at 22:35
  • @jotaelesalinas I read through the topic, doesn't seem to have the answer I am looking for. – Donovan G. Nov 22 '18 at 23:18
  • So what I understood here is, you want to find out the duplicate entries, right? Also, are you comparing entries in 1 array or 2 arrays? – Harsh Shankar Nov 23 '18 at 01:22
  • Also, when I read the code again, I found it should only print the last entry, not all. Check the fiddle, http://cpp.sh/9s6m – Harsh Shankar Nov 23 '18 at 01:35
  • 1.) You should initialize `index` to an invalid value (e.g. -1) to detect whether you found a duplicate at all (and, of course, check this afterwards). 2.) Without knowing how `cityname`s in `cityArr` are stored this is hard to say. So far, (and beside of 1.)) your exposed code looks OK. If `cityArr[index].cityname` prints what it prints then this is probably what is stored in `cityArr[index].cityname`. I guess, something is wrong in your allocation of `cityname`s or how you terminate these entries. But this happens in the code you didn't expose. – Scheff's Cat Nov 23 '18 at 06:44

1 Answers1

0

What you are doing is good but you miss one thing, when i will be equal to j. To resolve this problem you can just do this :

int index;

for (int i = 0; strlen((cityArr+i)->cityname) != 0; i++) {
    for (int j = 0; strlen((cityArr+j)->cityname) != 0; j++) {
        if (i == j) {
            continue;
        }
        if (strcmp(cityArr[i].cityname, cityArr[j].cityname) == 0) {
            index = i;
        }
    }
}

printf("%s\n", cityArr[index].cityname);

With this, if i is equal j, the second for will pass to the next iteration without testing if city names are the same.