双向链表的存储读出数据修改的程序//为何崩溃,该如何处理
双向链表的存储读出数据修改的程序//为何崩溃
------解决方案--------------------
- C/C++ code
#include <iostream> #include <string> #include <cstring> #include <fstream> using namespace std; struct table{ table():next(NULL),prev(NULL){}; table(int id_t,char* name_t,int age_t): id(id_t),name(name_t),age(age_t),next(NULL),prev(NULL){} int id; char* name; int age; table* next; table* prev; }; table* ifRead(char* file)//读出文件函数实现 { table* head=NULL,*memory=NULL,*cur=NULL,*tail=NULL; ifstream iff(file); iff.seekg(0,ios::beg); char str[8]=""; int count=0; while(iff.getline(str,sizeof(str),' '))//读出操作与存入链表中 if(++count==1) { memory = new table; if(head==NULL&&tail==NULL) { head=memory; tail=memory; int temp=0; int i=0; while(str[i]!='\0') { str[i]-=48; temp=temp*10+str[i]; i++; } memory->id=temp; } else { tail->next=memory; memory->prev=tail; tail=memory; int temp=0; int i=0; while(str[i]!='\0') { str[i]-=48; temp=temp*10+str[i]; i++; } memory->id=temp; } } else if(count==2) { memory->name=str; } else if(count==3) { int temp=0; int i=0; while(str[i]!='\0') { str[i]-=48; temp=temp*10+str[i]; i++; } memory->age=temp; count=0; } iff.close(); return head; } void revise(table* head,char* fname)//修改完毕并存入文件中 { cout<<"input student's id that you want to midfy"<<endl; int id_modfiy; cin>>id_modfiy; table* cur=head; while(cur!=NULL) { if(cur->id==id_modfiy) { cout<<"1.Do you want to modify the student's id" <<"2.Do you want to modify the student's name" <<"3.Do you want to modify the student's age" <<"4.Do you want to modify the student's whole information" <<endl; int choice; cin>>choice; switch(choice) { case 1:cin>>cur->id;break; case 2:cin>>cur->name;break; case 3:cin>>cur->age;break; case 4:cin>>cur->name>>cur->id>>cur->age;break; } } cur=cur->next; } } int main() { char fname[10]=""; cout<<"input student's information table file name"<<endl; cin>>fname; table* head=ifRead(fname); revise(head,fname); }
------解决方案--------------------
- C/C++ code
if(++count==1) { memory = new table; if(head==NULL&&tail==NULL) { /*为什么不初始化memory节点内部的next和prev指针???name指针为什么不申请内存存放数据,而是指向了一个你用来存放临时数据的buff呢??还是就是与这个if匹配的else有何作用呢?我发现好像根本就不可能进入到这个else里面。*/ head=memory; tail=memory; int temp=0; int i=0; while(str[i]!='\0') { str[i]-=48; temp=temp*10+str[i]; i++; } memory->id=temp; } else { tail->next=memory; memory->prev=tail; tail=memory; int temp=0; int i=0; while(str[i]!='\0') { str[i]-=48; temp=temp*10+str[i]; i++; } memory->id=temp; } }