2012-05-24 146 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添加一些標準檢查以檢查您正在閱讀的內容是否有效應該執行此操作。