0

我有以下代码,我想构建一个对象。我怎么能做到?有任何想法吗?该类的类型为 {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
4

1 回答 1

2

重载 Student 类型的输入和输出操作符对你有用吗?

#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 添加一些标准检查以检查您正在阅读的内容是否有效。

于 2012-11-15T00:14:48.823 回答