从文件读取并将其内容放入对象数组,并对它们进行排序

问题描述 投票:0回答:1

我一直在尝试从文件中读取文件,并将其内容放入类中的对象数组,并尝试使用QuickSort,MergeSort等对它们进行排序。但是我的问题是如何从文件中实际读取并将它们放置到基于txt文件的动态大小的数组中,并放入主文件中。我确实了解ifstream以及如何打开和关闭文件。 (分配背景:https://docdro.id/PCb1ZBY

我在课堂上有这个,但我不知道从哪里开始。

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;}



};

我正在阅读的文本文件:

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

我还希望根据用户的选择通过其GPA使用排序算法对数组进行排序。我已经创建了一个开关案例菜单和排序功能(MergeSort和QuickSort),但是再次需要帮助,如何将文本文件的内容传递到对象数组中,然后将其用于main函数中。例如:

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);


    }    

}   
c++ arrays class sorting ifstream
1个回答
0
投票

您的ifstream对象应该足以从文本文件中获取输入。读取以下内容读取数据

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;
    }
}

然后您可以创建一个std::vector<Student>并创建您的自定义比较器

© www.soinside.com 2019 - 2024. All rights reserved.