Need help checking if array equals another array

closed account (EAp4z8AR)
I can not seem to figure out how to check if the arrays are equal, the first half works but when I try to run the for loops to check for duplicates, it just prints everything.


int main()
{
string name[5];
int i;

int j = i;
for (i=0; i<5; i++)
{
cout << "Please enter a name: ";
cin >> name[i];

for (j=0; j<5; j++)
{
name[j];

}
}

for (i=0; i<5; i++)
{
for (j=0; j<5; j++)
{
if(name[i] == name[j] )
{
cout << name[i] << " is a duplicate name!";
}
}
}
}
Last edited on
This makes no sense. There is only one array. You already know that the array is equal to itself.
The OP's question is mis-worded. He/She's trying to avoid duplicates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int main()
{
  // Start simple, use good variable names
  constexpr int MAX_NUM_NAMES = 5;
  string names[ MAX_NUM_NAMES ];
  int num_names = 0;

  while (num_names < MAX_NUM_NAMES)
  {
    cout << "Please enter a name: ";
    // Use the appropriate construct for input
    string name;
    getline( cin, name );

    // Find name in names[]
    // (If you do it here, you can avoid putting a duplicate in the array)
    for (int i = 0; i < num_names; i++)
    {
      if (name == names[ i ])
      {
        cout << name << " is a duplicate name!\n";
        continue;
      }
    }

    // If we get this far, name is not a duplicate. Add it:
    names[ num_names++ ] = name;
  }

If you wish to read all inputs and then just complain if there are duplicates:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int main()
{
  // Start simple, use good variable names
  constexpr int MAX_NUM_NAMES = 5;
  string names[ MAX_NUM_NAMES ];
  int num_names = 0;

  while (num_names < MAX_NUM_NAMES)
  {
    cout << "Please enter a name: ";
    // Use the appropriate construct for input
    string name;
    getline( cin, name );

    // Add the name regardless of potential repetition
    names[ num_names++ ] = name;
  }

  // Now check for duplicates. 
  // You were correct that a nested loop is necessary, but you do
  // not need to check an item against the others more than once
  for (int n1 = 0; n1 < num_names - 1; n1++)
  {
    for (int n2 = n1 + 1; n2 < num_names; n2++)
    {
      if (name[ n1 ] == name[ n2 ])
        cout << name[ n1 ] << " is a duplicate name!\n";
    }
  }

Hope this helps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
#include <string>

using namespace std;

 int main()
 {
     
 string name[5];
 
 for(int i = 0; i < 5; i++) {
    cout << "Please enter a name: ";
    getline(cin, name[i]);
 }

for(int i = 0; i < 5; i++) {
    for(int j = i + 1; j < 5; j++) {
        if(name[i] == name[j]) {
            cout << name[i] << " is a duplicate.\n";   
        }
    }
}

return 0;
}
Topic archived. No new replies allowed.