编写文本文件c ++

时间:2016-02-15 14:00:08

标签: c++

这是我的头文件Person.hpp:

#ifndef PERSON_HPP
#define PERSON_HPP

#include <iostream>
#include <string>
using namespace std;

class Person {
public:
    Person(string name_val = "", int id_val = 0);
    virtual void write(ostream& strm);
    virtual void read(istream& strm);
private:
    string name;
    int id;
};
ostream& operator<<(ostream& strm, Person& person);
istream& operator>>(istream& strm, Person& person);

Person::Person(string name_val, int id_val)
: name(name_val), id(id_val) {

}

void Person::write(ostream& strm) {
    strm << id << " " << name;
}

void Person::read(istream& strm) {
    strm >> id >> name;
}

ostream& operator<<(ostream& strm, Person& person) {
    person.write(strm);
    return strm;
}

istream& operator>>(istream& strm, Person& person) {
    person.read(strm);
    return strm;
}

#endif

和来自第一个Student.hpp的第二个头文件:

#ifndef STUDENT_HPP
#define STUDENT_HPP

#include <iostream>
#include <iomanip>
#include <string>
#include "Person.hpp"
using namespace std;

class Student {
public:
    Student(string name_val = "", int id_val = 0, double gpa_val = 0.0);
    void write(ostream& strm);
    void read(istream& strm);
private:
    double gpa;
};
ostream& operator<<(ostream& strm, Student& student);
istream& operator>>(istream& strm, Student& student);

Student::Student(string name_val, int id_val, double gpa_val)
: gpa(gpa_val) {

}

void Student::write(ostream& strm) {
    //wait for modify
}

void Student::read(istream& strm) {
    //wait for modify too.
}

ostream& operator<<(ostream& strm, Student& student) {
    student.write(strm);
    return strm;
}

istream& operator>>(istream& strm, Student& student) {
    student.read(strm);
    return strm;
}

#endif

和main.cpp:

#include <iostream>
#include <fstream>
#include "Person.hpp"
#include "Student.hpp"
using namespace std;
int main() {
    Student aStudent;

    ofstream outFile;
    outFile.open("Student.txt");

    cout << "Enter ID and name, and grade point average" << endl;
    while (cin >> aStudent) {
        outFile << aStudent << endl;
        cout << "Enter ID and name, and grade point average" << endl;
    }
    outFile.close();
}

我想收集这样的数据:

Enter ID and name, and grade point average
5601 Bird 3.01
Enter ID and name, and grade point average
5602 Bee 2.58
Enter ID and name, and grade point average
5603 Bow 4.00
Enter ID and name, and grade point average
^Z (terminates)

程序将创建文本文件名student.txt 并在此文本文件中收集ID和名称以及GPA。 (抱歉,代码很长。)

如何修改Student.hpp?

1 个答案:

答案 0 :(得分:0)

这很简单。您首先读/写基类(Person),然后读/写Student - 特定数据:

void Student::write(ostream& strm) {
    Person::write(strm);
    strm << gpa;
}

void Student::read(istream& strm) {
    Person::read(strm);
    strm >> gpa;
}

话虽如此,这可能是operator<<operator>>,不需要read / write函数(除非您需要它们)。此外,请开始使用const关键字,例如:

write(ostream& strm) const;
//                   ^^^^^

ostream& operator<<(ostream& strm, Student const& student);
//                                         ^^^^^
相关问题