2012-05-27 45 views
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 
+1

之前为int提取创建新的stringstream对象,或者消耗所有内容。您可以将您正在尝试阅读的文件的内容也放在此处。以及Student类的定义。 –

+0

补充说,我希望它有帮助。 –

+0

不要使用''eof()'那样,参见http://stackoverflow.com/a/6512278/4279 – jfs

回答

3

当你调用s = ss.str();,它不消耗缓冲区,因此下次您尝试提取int时,由于ss缓冲区仍包含初始字符串(和而不仅仅是您在末尾附加的数字的字符串表示)。您可以在尝试提取int s

+1

...或用'ss.str(“”)清空现有的stringstream对象;'' – aldo