将文件数据赋值给结构数组



我正在尝试将输入文件中的一行数据分配给一个结构体数组。

这是我的结构体:

struct student
    {
        int ID;
        int hours;
        float GPA;
    };
    student sStudents[MAX_STUDENTS]; // MAX_STUDENTS = 10

地点:

for (int i = 0; !inputFile.eof(); i++)
{
    getline(inputFile, dataLine);
    cout << dataLine << endl; // Everything outputs perfectly, so I know dataLine is getting the correct information from getline()
            //??
}

在谷歌上爬了一个小时后,我仍然不知道如何将我的getline()数据放入每个struct数组中。

我试过了,

sStudents[i] = dataLine;
sStudents[i] << dataLine;
sStudents.ID = dataLine;

这是我的数据文件:

1234  31  2.95
9999  45  3.82
2327  60  3.60
2951  68  3.1
5555  98  3.25
1111  120 2.23
2222  29  4.0
在这一点上,我变得很沮丧,我只是不知道该做什么。在这一点上,我确信我做得完全不正确,但不确定如何从这里继续。我知道sStudents有10个元素,这很好,但我如何将输入文件中的值分别输入到。id,。hours,。gpa中呢?也许getline()在这里使用不正确?

您可以简单地执行以下操作:

int ID = 0;
int hours = 0;
float GPA = 0.0;
int i = 0;
ifstream inputFile("data.txt");
while (inputFile >> ID >> hours >> GPA)
{
   sStudents[i].ID = ID;
   sStudents[i].hours = hours;
   sStudents[i].GPA = GPA;
   i ++;
}

使用标准库的建议。

#include<iostream>
#include<fstream>
#include<vector>
// your data structure
struct Student {
  int id;
  int hours;
  float gpa;
};
// overload the input stream operator
bool operator>>(std::istream& is, Student& s) {
  return(is>>s.id>>s.hours>>s.gpa);
}
// not necessary (but useful) to overload the output stream operator
std::ostream& operator<<(std::ostream& os, const Student& s) {
  os<<s.id<<", "<<s.hours<<", "<<s.gpa;
  return os;
}

int main(int argc, char* argv[]) {
  // a vector to store all students
  std::vector<Student> students;
  // the "current" (just-read) student
  Student student;
  { // a scope to ensure that fp closes                                     
    std::ifstream fp(argv[1], std::ios::in);    
    while(fp>>student) {
      students.push_back(student);
    }
  }
  // now all the students are in the vector
  for(auto s:students) {               
    std::cout<<s<<std::endl;
  }
  return 0;
}

使用>>操作符从输入流中获取数据。所以:

int i;
file >> i;

从文件中提取单个整数。默认情况下,它以空格分隔。使用它,看看你是否更进一步

最新更新