Consider a text file of names, with one name per line, that has been compiled from several different sources. A sample is shown in the following:
Brooke Trout
Dinah Soars
Jed Dye
Brooke Trout
Jed Dye
Paige Turner
There are duplicate names in the file. We would like to generate an invitation list but do not want to send multiple invitations to the same person. Write a program that eliminates the duplicate names by using the set template class. Read each name from the file, add it to the set, and then output all names in the set to generate the invitation list without duplicates.
C++ program code:
#include <iostream>
#include <fstream>
#include <string>
#include <set>
using namespace std;
int main()
{
// Assuming the names are stored in a file named "names.txt"
ifstream inputFile("names.txt");
string name;
set<string> uniqueNames;
// Read each name from the file and add it to the set
while (getline(inputFile, name))
{
uniqueNames.insert(name);
}
// Output the invitation list without duplicates
cout << "Invitation List without Duplicates:" << endl;
for (const auto& uniqueName : uniqueNames)
{
cout << uniqueName << endl;
}
return 0;
}
Input file (names.txt) data:
Brooke Trout
Dinah Soars
Jed Dye
Brooke Trout
Jed Dye
Paige Turner
Output of the program code:
Invitation List without Duplicates:
Brooke Trout
Dinah Soars
Jed Dye
Paige Turner