2012-05-24 101 views
0

我有以下代码,我想构建一个对象。我怎么能这样做?有任何想法吗?该类是{sting,int,int}类型。从txt文件行创建类对象

代码:

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

保存到文件funcntion:

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

你会好吗向我们展示'studs.txt'包含什么? –

+0

该文件是可重写的文件。我确实保存了我的工作。 –

+0

_limit_是什么意思? ['std :: getline()'](http://en.cppreference.com/w/cpp/string/basic_string/getline)将读取换行符(并放弃它)。不要使用'while(!fl.eof()){}',立即检查if(getline(...))是否成功。 – hmjd

回答

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添加一些标准检查以检查您正在阅读的内容是否有效应该执行此操作。