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!";
}
}
}
}
int main()
{
// Start simple, use good variable names
constexprint 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:
int main()
{
// Start simple, use good variable names
constexprint 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";
}
}