我是C++編程的初學者,我有一個關於從文件讀入特定類對象的問題,其中一個是數組。從文件讀取到不同的類對象
我的類對象:
const int SIZE_OF = 5;
class Student
{
public:
Student();
Student(const Student &);
Student(string, int, int, int, int, int);
friend std::istream& operator >> (std::istream& in, Student& S);
void display();
private:
string lastName;
int grades[SIZE_OF];
};
CPP文件來定義功能:
Student::Student()
{
int i;
string lastName = "default";
for (i = 0; i < 5; i++)
{
grades[i] = 0;
}
}
Student::Student(const Student & S)
{
int i;
lastName = S.lastName;
for (i = 0; i < 5; i++)
{
grades[i] = S.grades[i];
}
}
Student::Student(string S, int a, int b, int c, int d, int e)
{
lastName = S;
grades[0] = a;
grades[1] = b;
grades[2] = c;
grades[3] = d;
grades[4] = e;
}
std::istream& operator >> (std::istream& in, Student& S)
{
std::string line;
std::getline(in, line);
in >> S.lastName >> S.grades[0] >> S.grades[1] >> S.grades[2] >> S.grades[3] >> S.grades[4];
getline(in, S.lastName);
return in;
}
void Student::display()
{
int i;
int sum = 0;
double average;
cout << "Last Name: " << lastName << endl;
cout << "Grades: " << endl;
for (i = 0; i < 5; i++)
{
cout << grades[i] << endl;
}
for (i = 0; i < 5; i++)
{
sum = sum + grades[i];
}
average = sum/5;
cout << "Average: " << average;
}
我需要做的是從文件中讀取並保存Student
類的lastName
對象下的叫什麼名字。然後我需要將每個等級保存在數組對象中。然後,我需要爲下一個名稱創建一個新的Student
類對象,併爲4個名稱重複該過程。我從閱讀的文件:
George
75,85,95,100,44
Peter
100,100,100,100,100
Frank
44,55,66,77,88
Alfred
99,88,77,66,55
我似乎不明白的是如何將文件讀入不同的類對象。例如,我將有4個學生類的對象,前兩行將被讀取到第一個對象,然後接下來的兩行是第二個對象,依此類推。 –