2
我有休闲功能,我无法得到它为什么不起作用。保存数据后保存正确,但读取它时,它不会读取整数部分。从txt文件读取和创建对象
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;
}
};
文件:(在打印所有INT的是0,因为我initializate负载函数的对象)
maier tsdar,2,0
staedfsgu aldasn,0,3
pdasdp aasdela,323,23
marsdaciu baleen,234,4534
madsd,234,2345
之前为
int
提取创建新的stringstream对象,或者消耗所有内容。您可以将您正在尝试阅读的文件的内容也放在此处。以及Student类的定义。 –补充说,我希望它有帮助。 –
不要使用''eof()'那样,参见http://stackoverflow.com/a/6512278/4279 – jfs