阅读与阅读从txt文件创建一个对象

时间:2012-05-27 16:01:30

标签: c++

我有休假功能,我无法理解为什么它不起作用。保存后数据保存正确,但在读取数据时,它不会读取int部分。

void StudentRepository::loadStudents(){
    ifstream fl;
    fl.open("studs.txt");
    Student st("",0,0);
    string str,s;
    stringstream ss;
    int i;
    int loc;
    if(fl.is_open()){
        while(!(fl.eof())){
            getline(fl,str);
            loc = str.find(",");
            ss << str.substr(0,loc);
            s = ss.str();
            st.setName(s);
            str.erase(0,loc);
            loc = str.find(",");
            ss << str.substr(0,loc);
            ss >> i;
            st.setId(i);
            str.erase(0,loc);
            ss >> i;
            st.setGroup(i);
            students.push_back(st);

        }
    }
    else{
        cout<<"~~~ File couldn't be open! ~~~"<<endl;
    }
    fl.close();
}

编辑:

class Student {
private:
    string name;
    int ID;
    int group;



public:
Student(string name, int id, int gr ):name(name),ID(id),group(gr){}

void setId(int value)       {group = value;}
void setGroup(int value)    {ID = value;}
void setName(string value)  {name = value;}
int getGroup()              const{return group;}
int getID()              const{return ID;}
    string getName()            const{return name;}

    friend ostream& operator << (ostream& out, const Student& student)
    {
        out << student.name << " " << student.ID << " " << student.group <<endl;
        return out;
    }
};

file :(在打印时,所有int&#39; s为0,因为我在加载函数中初始化对象)

maier tsdar,2,0
staedfsgu aldasn,0,3
pdasdp aasdela,323,23
marsdaciu baleen,234,4534
madsd,234,2345

1 个答案:

答案 0 :(得分:3)

当您调用s = ss.str();时,它不会使用缓冲区,因此下次尝试提取int时,提取会失败,因为ss缓冲区仍包含初始值string(而不仅仅是您在末尾附加的数字的字符串表示)。您可以为int提取创建新的字符串流对象,或者在尝试提取int之前使用所有内容