SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Standard Template Library
Exercise:
Programming Projects
Question:12 | ISBN:9780132846813 | Edition: 5

Question

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.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.