queenbelle02
queenbelle02

Reputation: 1

How to read both last and first names in text file in C++

I am a very novice in C++. Just trying to learn one month ago. I am trying to figure out this problem:

A teacher has asked all her students to line up single file according to their last name.

Write a program that will read in a file of names. Names should be read until there are no more names to be read. The file I have has both last name and first name. I would like to display both names.

This is what I have so far, but it sorts by first name and just displays first name. How can I get it to sort by last name and display both last and first name?

Thank you.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    ifstream inputFile;

    string lastname, firstname, 
        first,
        last;

    inputFile.open("RandomNames.txt");

    if (inputFile)
    {
    
        inputFile >> lastname;
        first = last = lastname;

        while (inputFile >> lastname)
        {
            if (lastname < first)
                first = lastname;

            else if (lastname > last)
                last = lastname;
        }

   
        inputFile.close();
    }

    cout << "First student in line = "
        << first;

    cout << "Last student in line  = "
        << last;

    return 0;
}

Upvotes: 0

Views: 846

Answers (1)

east1000
east1000

Reputation: 1294

The contents of the RandomNames.txt file containing names and surnames are as follows.

Allan Garnier
Kingston Arnold
Hayley Jackson
Carmel Harrell
Lee Erickson

Below is the program that does the job you want.

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<std::string>fullNames;

    // Open the file and check, if it could be opened. (Don't forget to write the path to your RandomNames.txt file.)
    if (std::ifstream dataStream{ "C:\\Users\\*****\\******\\RandomNames.txt" }; dataStream) {

        // Read all values in vector data
        std::vector<std::string> data(std::istream_iterator<std::string>(dataStream), {});

        for (size_t i = 0; i < data.size(); i += 2)
        {
            fullNames.push_back(data[i + 1] + " " + data[i]);
        }

        //Sort vector elements by last name.
        std::sort(fullNames.begin(), fullNames.end());

        //Print names sorted by last name.
        for (size_t i = 0; i < fullNames.size(); i++)
        {
            std::cout << fullNames[i] << "\n";
        }
        // And close the file
        dataStream.close();
        return 0;
    }
}

The output of RandomNames.txt file sorted by last name is as follows.

Arnold Kingston
Erickson Lee
Garnier Allan
Harrell Carmel
Jackson Hayley

Upvotes: 2

Related Questions