从文件读取到不同的类对象

时间:2016-07-21 20:19:48

标签: c++ arrays class sorting fstream

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

我需要做的是从文件中读取并将名称保存在lastName类的Student对象下。然后我需要保存数组对象中的每个等级。然后我需要为下一个名称创建一个新的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

1 个答案:

答案 0 :(得分:1)

您的以下功能似乎有误:

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

你读了两次lastName,你不要忽略&#39;,&#39;性格......尝试这样的事情:

std::istream& operator >> (std::istream& in, Student& S)
{
    char dummy;
    in >> S.lastName >> S.grades[0] 
       >> dummy >> S.grades[1] 
       >> dummy >> S.grades[2] 
       >> dummy >> S.grades[3] 
       >> dummy >> S.grades[4];

    return in;
}

更新:   如果考虑lastName中的空格,则必须更改第一行以使用std :: getline,如下所示:

std::istream& operator >> (std::istream& in, Student& S)
{
    char dummy;
    std::getline(in, S.lastName) 
    in >> S.grades[0] 
       >> dummy >> S.grades[1] 
       >> dummy >> S.grades[2] 
       >> dummy >> S.grades[3] 
       >> dummy >> S.grades[4];
    in.ignore(); // remove last '\n'
    return in;
}

然后:

int main()
{
    Student s;
    std::vector<Student> all;

    while (cin>>s)
      all.push_back(s);
}

......还有......足够的更新!