从文本文件行构建类对象

时间:2012-05-24 15:30:22

标签: c++

我有以下代码,我想构建一个对象。我怎么能这样做?有任何想法吗?该类的类型为{sting,int,int}。

代码:

void StudentRepository::loadStudents(){
    ifstream fl;
    fl.open("studs.txt");
    Student A();
    if(fl.is_open()){
        while(!(fl.eof())){
            getline(???); //i dont knwo houw coudl i limit what i want were...

        }
    }
    else{
        cout<<"~~~ File couldn't be open! ~~~"<<endl;
    }
}

保存到文件功能:

void StudentRepository::saveStudents(){
    ofstream fl;
    fl.open("studs.txt");
    if(fl.is_open()){
        for(unsigned i=0; i<students.size(); i++){
            fl<<students[i].getName();
            fl<<",";
            fl<<students[i].getID();
            fl<<",";
            fl<<students[i].getGroup();
            fl<<","<<endl;
        }
    }
    else{
    cout<<"~~~ File couldn't be open! ~~~"<<endl;
}

我试图实施一些限制,但这不起作用......我怎么能这样做?

最初我只是将对象写入文件但是很难让它们回到对象.... 文件内容:

maier ewew 123 232
tudor efsw 13 2323

1 个答案:

答案 0 :(得分:2)

重载学生类型的输入和输出操作符会为你工作吗?

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class Student {
public:
    Student() : name(""),id(0),group(0) {}
    Student(const string &_name, const int &_id, const int &_group) : name(_name), id(_id), group(_group) {}

    friend ostream &operator<<(ostream &out, const Student &stud);
    friend istream &operator>>(istream &in, Student &stud);
private:
    string name;
    int id;
    int group;
};    

ostream &operator<<(ostream &out, const Student &stud) {
    out << stud.name << " " << stud.id << " " << stud.group << endl;
    return out;
}

istream &operator>>(istream &in, Student &stud) {
    string name, surname;
    in >> name >> surname >> stud.id >> stud.group;
    stud.name = name + " " + surname;
    return in;
}    

int main(int argc, char **argv) {

    Student john("john doe", 214, 43);
    Student sally("sally parker", 215, 42);
    Student jack("jack ripper", 114, 41);

    ofstream out("studentfile.txt");
    out << john;
    out << sally;
    out << jack;
    out.close();

    Student newstud;
    ifstream in("studentfile.txt");
    in >> newstud;
    cout << "Read " << newstud;
    in >> newstud;
    cout << "Read " << newstud;
    in >> newstud;
    cout << "Read " << newstud;
    in.close();

    return 0;
}    

为I / O添加一些标准检查以检查您正在阅读的内容是否有效。