Recognizing duplicate elements in an array?

How do I make my program output 'duplicate name' for values inside an array? I can't seem to understand how to write it so it will check for a repeated element when the user inputs the names.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include <iostream>

using namespace std;

int main() {
    
    string names[5];        //array with 5 names
    string input;
    
   for (string input : names){
        cout << "Please enter a name: ";   
        cin >> input;
    }
   
    for (int check = 1; check-1; check++){
    
        if (input == names[check]){
            cout << input << " is a duplicate name!" << endl;
        }
    }
}
brute force works. but 2 issues:
check should maybe start at zero and go to your current (if you have read in 3, it goes 0, 1, 2 to check the fourth to see if it was already there). If only you had a loop counting variable in that outer for loop...

second, your loop structure looks wrong. it should be
for(... names)
{
get a new name.
for(all the existing names you have so far, as above, 0, 1, 2 when input is 4th one)
check input

}

what you have is
for(names)
//end this for
for(..)
//check only the final input.




I think you should check first the input before you input it into the array.
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
30
31
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() 
{
  const int N = 5;
  string names[N];        //array with 5 names
  string input;
  int count = 0;

  while (count < N)
  {
    cout << "Please enter name " << count + 1 << ": ";
    cin >> input;
    if (find(names, names + N, input) !=  names + N)
    {
      cout << "duplicate name...\n";
    }
    else
    {
      names[count] = input;
      count++;
    }
  }
  cout << "The names you entered\n";
  for (const string& name: names)
    cout << name << '\n';
}


I don't think an array is the best container for this task. A better option would be to use std::set or std::unordered_set
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <set>
#include <string>
using namespace std;

int main()
{
   const int NUMNAMES = 5;     // Number of DISTINCT names required
   set<string> names;

   while ( names.size() < NUMNAMES )
   {
      string input;
      cout << "Enter a name: ";   cin >> input;
      if ( !names.insert( input ).second ) cout << "Duplicate name\n";
   }

   cout << "\nNames are:\n";
   for ( string s : names ) cout << s << '\n';
}
Enter a name: Charles
Enter a name: Andrew
Enter a name: Edward
Enter a name: Charles
Duplicate name
Enter a name: Edward
Duplicate name
Enter a name: Martin
Enter a name: Samuel

Names are:
Andrew
Charles
Edward
Martin
Samuel
Last edited on
Topic archived. No new replies allowed.