2

我有休闲功能,但我不明白为什么它不起作用。保存数据后保存正确,但在读取数据时,它不会读取 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;
    }
};

文件:(在我在加载函数中初始化对象时,所有 int 都为 0)

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

1 回答 1

3

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

于 2012-05-27T16:08:39.610 回答