注册 登录
编程论坛 C++教室

关于写入文件数据时出现的一点问题

yijing21 发布于 2008-04-19 09:45, 464 次点击
cout<<"请输入要删除的学号:";
    string str;
    cin>>str;
    list<student> ivec;
    ifstream in;
    in.open("stu.txt",ios::in);
    while(in)
    {
        student stu;
        in>>stu.num>>stu.name>>stu.score[0]>>stu.score[1]>>stu.score[2];
        ivec.push_back(stu);
    }
    
    for(list<student>::iterator it=ivec.begin();it!=ivec.end();)
    {
        if(it->num==str)
            it=ivec.erase(it);
        else
            ++it;
    }         

         list<student> ivec;
         ofstream out;
    out.open("stu.txt",ios::out);
    for(list<student>::iterator y=ivec.begin();y!=--ivec.end();++y)
    {
        out<<y->num<<"\t";
        out<<y->name<<"\t";
        out<<y->score[0]<<"\t";
        out<<y->score[1]<<"\t";
        out<<y->score[2]<<"\t";
    }

把一个结构体的数据写入文件 为什么迭代器那里要自减一次呢  不然会出现
03042201    ty    89    89    89    03042222    fg    85    81    83    
03042256    ty    89    89    89            89    89    89    
最后一项错误数据不知道是怎么出来的它3个数跟倒数第二项的数据是一样的 但是它没有前面的两项数据(学号和姓名)

[[it] 本帖最后由 yijing21 于 2008-4-19 09:46 编辑 [/it]]
5 回复
#2
yijing212008-04-19 20:51
没人知道吗 自己顶一下
#3
sunkaidong2008-04-19 21:00
ivec.erase(it)
No reallocation occurs, so iterators and references become invalid only from the first element erased through the end of the sequence.
#4
sunkaidong2008-04-19 21:02
你的操作引起iterators失效了...
#5
yijing212008-04-20 10:33
应该不是迭代器失效的问题吧   是在写入的时候多出来一些数据  不知道怎么产生,就算是把erase()注释掉 结果还是产生这些数据啊
#6
sunkaidong2008-04-20 10:40
是迭带器器的问题..不相信,你可以找到之后删除然后从跳出循环..然后在从新用一个迭带循环看看...如果找出处是在c++primer关于模板上有...
1