c++双向链表程序//为何程序崩溃?该如何处理
c++双向链表程序//为何程序崩溃?
- 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; }; void ofRead(const char* file,table* head)//写入文件函数实现 { ofstream of(file); of.seekp(0,ios::beg); table* cur=head; do{ of<<cur->id<<' '<<cur->name<<' '<<cur->age<<' '; cur=cur->next; }while(cur==NULL); of.close(); } void Create()//创建链表并写入文件 { table* head=NULL,*tail=NULL,*memory=NULL; string str("Yes"); char choice[4]=""; do{ cout.flush(); int id,age; char* name=NULL; cout<<"input new student with student's name,id and age into the table.txt"<<endl; cin>>name>>id>>age; memory= new table(id,name,age); if(head==NULL&&tail==NULL) { head=memory; tail=memory; } else { tail->next=memory; memory->prev=tail; tail=memory; } printf("choose Y to go ahead,choose N to quit:"); cout.flush(); cin>>choice; }while(str==choice); ofRead("c:\\table.txt",head); } table* ifWrite(char* file)//读出文件函数实现 { static table* head=NULL,*memory=NULL;//静态存储 table* 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; memory->id=(int)str; } } 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; 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; } ofRead(fname,head); } int main() { Create(); cout<<"Do you want to modify the student information?(yes or no)"<<endl; string str("yes"); char choice[4]=""; cin>>choice; if(str==choice)//选择是否文件读出与修改 { char fname[10]=""; cout<<"input student's information table file name"<<endl; cin>>fname; table* head=ifWrite(fname); revise(head,fname); } if(strcmp(choice,"no")==0) { cout<<"your operaion complete."<<endl; } }