首页 > 解决方案 > 从 txt 文件中提取信息并存储到单独的数组中

问题描述

我有一个任务需要一个函数,该函数应该从单独的 txt 文件中读取学生的数据并将数据存储到结构 [] 中。

例如,如果文本文件显示:

John Doe
50 60 70
9 9 
1 2 3
50 80 90

它将数据存储到一个动态分配的结构“studentData”中,该结构包括:

struct Student{
string name;
  double * exams;
  double * quizzes;
  double * hw;
  double * labs;
}
Student* studentsData; // pointer to base address of dynamically allocated array to store data read from file
  ifstream inFile;
  string line;

  inFile.open("grades.txt");
  assert(inFile); // if failed to open file, terminate program with an error message

  //allocate memory for the dynamic array studentsData
   studentsData = new Student[numStudents];
 // for(int i = 0; i < numStudents ; i++)
 while (getline(inFile,line))
      {
          inFile >> line >> studentsData->exams >> studentsData->quizzes >> studentsData->labs >>studentsData->hw;
          studentsData.name = line;


  //store student read from file into the array

  inFile.close();
  return studentsData;

标签: c++

解决方案


推荐阅读