简体   繁体   中英

Reading from file and placing its contents into an array of objects, and sorting them

I've been trying to read from a file and place its contents to a array of objects in a class and trying to sort them with QuickSort, MergeSort, etc. as an assignment. But my problem is how to actually read from the file and placing them into a dynamically sized array based on the txt file and into the main. I do know about ifstream and how to open and close a file. (Assignment background: https://docdro.id/PCb1ZBY )

I have this for my class but I don't know where to begin.

class Student
{
private:
  string firstName;
  string lastName;
  double GPA;
public:
Student() { firstName = ""; lastName = ""; GPA = 0.0; }
// Default Constructor
Student(string f, string l, double g) {firstName = f; lastName = l;}

void setFName(string f) {firstName = f;}
string getFName() { return firstName;}

void setLName(string l) {lastName = l;}
string getLName() {return lastName;}

void setGPA(double g) {GPA = g;}
double getGPA() { return GPA;}



};

Text file that I'm reading from:

Andrew Koch 2.0
Landyn Adkins 2.6
Jakobe Carey 2.7
Troy Murray 2.9
Cullen Dyer 3.0
Zaire Murphy 2.2
Zaniyah Martinez 3.7
Nolan Lynch 0.6
Josh Harris 1.3
Alejandra Stevens 2.1
Reginald Graves 1.9
Raelynn Castro 3.8
Oscar Norman 1.1
Emerson Randolph 4.0
Mitchell Roman 3.0
Alessandro Huff 0.9
Clarissa Rocha 3.1
Pedro Acevedo 1.1
Katelyn Gilmore 1.9
Julianna Carroll 4.0

I also want to sort this array by using sort algorithms by their GPA based on the choice of the user. I have created a switch case menu and the sorting functions (MergeSort and QuickSort), but again, need help how to pass the contents of the text file into an array of objects and then use them into the functions in main. EX:

void heapSort(int arr[], int size)
{
    for (int index = size / 2 - 1; index >= 0; index--)
    {
        maxHeapify(arr, size, index); // already written but not included in this post

    }    

    for ( int index = size - 1; index >= 0; index--)
    {
        swap(&arr[0], &arr[index]);

        maxHeapify(arr, size, index);


    }    

}   

You ifstream object should be enough to get the input from the text file. Read the following read the data

std::ifstream inputFile("input.txt");
std::string firstName, lastName;
double gpa;
if (inputFile.is_open()) {
    while (!inputFile.eof()) {
        inputFile >> firstName >> lastName >> gpa;
        std::cout << firstName << "," << lastName << "," << gpa << std::endl;
    }
}

You can then create a std::vector<Student> and create your custom comparator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM