【问题标题】:Reading from file and placing its contents into an array of objects, and sorting them从文件中读取并将其内容放入对象数组中,并对它们进行排序
【发布时间】:2020-02-04 08:34:50
【问题描述】:

我一直在尝试从文件中读取内容并将其内容放入类中的对象数组中,并尝试使用 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 使用排序算法对这个数组进行排序。我已经创建了一个 switch case 菜单和排序函数(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】:

    您的 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&lt;Student&gt; 并创建您的自定义比较器

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 2013-01-28
      • 2020-11-18
      相关资源
      最近更新 更多