这段代码为什么崩溃?
lrecord是list容器,元素为含有整型、浮点、string的结构。要求是从一个文件里读取数据。确保文件打开正确,但是在读取第一条之后,往lrecord里添加新元素时就崩溃了程序代码:
while(!feof(fin)) { lrecord.push_back(nrecord); fread(&nrecord,sizeof(record),1,fin); }
#include <iostream> #include <cstdlib> #include <cstdio> #include <list> using namespace std; typedef struct rr { int id,num; double price; string name; }record; int main() { record nrecord; list<record> lrecord; list<record>::iterator rite; int total=-1; FILE *fin,*fout; char look; cout<<"请输入要处理的商品数量,100以内,0表示建立新文件:"; cin>>total; while(total<0||total>100) cout<<"输出有误,请重新输入:"; if(total==0) { fout=fopen("commodity.dat","wb"); } else { if(!(fin=fopen("commodity.dat","rb"))) { cout<<"对不起,文件不存在。"; return 0; } fread(&nrecord,sizeof(record),1,fin); while(!feof(fin)) { lrecord.push_back(nrecord); fread(&nrecord,sizeof(record),1,fin); } fclose(fin); cout<<"是否查看原来的记录?y/n"; cin>>look; if(look=='y'||look=='Y') { rite=lrecord.begin(); if(rite==lrecord.end()) cout<<"无记录。"<<endl; else for(;rite!=lrecord.end();++rite) { cout<<"ID"<<rite->id<<" 名称"<<rite->name<<" 数量"<<rite->num<<" 价格"<<rite->price<<endl; } } fout=fopen("commodity.dat","wb"); while(total--) { cout<<"请输入商品名称:"; cin>>nrecord.name; cout<<"请输入另外三个数据:"; cin>>nrecord.id>>nrecord.num>>nrecord.price; for(rite=lrecord.begin();rite!=lrecord.end()&&rite->id<nrecord.id;++rite); if(rite!=lrecord.end()&&rite->id==nrecord.id) *rite=nrecord; else lrecord.insert(rite,nrecord); } for(rite=lrecord.begin();rite!=lrecord.end();++rite) { fwrite(&(*rite),sizeof(record),1,fout); cout<<"ID"<<rite->id<<" 名称"<<rite->name<<" 数量"<<rite->num<<" 价格"<<rite->price<<endl; } fclose(fout); } cout<<"文件已保存,谢谢使用。"; return 0; }