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.
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.
#include <iostream>
#include <set>
#include <string>
usingnamespace std;
int main()
{
constint 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