乱逛的鬼 乱逛的鬼
关注数: 1 粉丝数: 13 发帖数: 92 关注贴吧数: 2
求大神帮忙看下为什么会崩溃 能运行,但是录入两段以上信息时直接删除最后一段就会直接报错。求解答 #include<iostream> #include<string>//字符串头文件类用于保存使用字符 using namespace std; class book { public: int num; float price; book *next; }; book*head=NULL; bool check(string str) { for(int i=0;i<str.length();i++)//此循环判断输入是否为数字且不包括“.” { if((str[i]>'9'||str[i]<'0')&&(str[i]!='.')) return false; } return true; } book*check() { book *p1,*p2; p1=new book; head=p1; p2=p1; cout<<"请输入编号以0结束:"<<endl; string str; cin>>str; while(!check(str))//使用上文的str进行判断 { cout<<"输入的不是数字请按0返回!"<<endl; cin>>str; } p1->num=atoi(str.c_str());/*保存书籍编号将字符串转换为整数且赋值给p1节点的num成员*/ if(p1->num!=0) /*(只接收C语言字符串,在使用是仍然需要转换。c_str转换函数由string类提供调用时需要使用xxx.格式来调用)*/ { cout<<"请输入书的价格:"<<endl; string str; cin>>str; while(!check(str))//使用上文的str进行判断 { cout<<"输入的不是数字请按0返回!"<<endl; cin>>str; } p1->price=atof(str.c_str());//保存价格将字符串转换为浮点且赋值给p1节点的price成员 } else { delete p1; p2->next=NULL; head=NULL; return head; } while(p1->num!=0) { p2=p1; p1=new book; cout<<"请输入编号以0结束:"<<endl; cin>>str; while(!check(str))//使用上文的str进行判断 { cout<<"输入的不是数字请按0返回!"<<endl; cin>>str; } p1->num=atoi(str.c_str()); if(p1->num!=0) { cout<<"请输入书的价格:"<<endl; cin>>str; while(!check(str))//使用上文的str进行判断 { cout<<"输入的不是数字请按0返回!"<<endl; cin>>str; } p1->price=atof(str.c_str()); } p2->next=p1; } delete p1; p2->next=NULL; return head; } void showbook(book*head)//显示已录入的数据 { cout<<endl <<"图书信息如下:"<<endl; while(head) { cout<<"图书编号:"<<head->num<<'\t' <<"图书价格:"<<head->price<<endl; head=head->next;//获得下一个节点的信息并且赋值给head } } void dlt(book*head,int num)//删除节点中某个环节 { book*l; if(head->num==num)//判断是否为第一个节点 { l=head; head=head->next; ::head=head;//将局部变量的head赋值给全局变量的head(调用全局变量操作符"::") delete l;//删除以前的头节点 cout<<"操作成功/n"; return;//void没有返回值 } while(head) { if(head->next=NULL)//不存在下一个节点 { cout<<"找不到要删除的编号。/n"; return; } if(head->next->num==num)//存在下一个节点 { l=head->next;//将下一个节点赋给l head->next=l->next;//将第一个节点与第二个节点建立联系 delete l;//删除旧节点 cout<<"删除成功!"<<endl; return; } head=head->next;//确认是否为最后一个节点 } cout<<"找不到要删除的编号!"<<endl; } void insert(book*head,int num,float price)//定义插入函数(不进行排序的话) { book*list=new book;//创建一个新节点,且用list指针指向该节点 list->num=num; list->price=price; list->next=head; ::head=list; } int main() { head=check(); showbook(head);//显示数据状态 cout<<"请输入您要删除的编号:\n"; int BookNum; cin>>BookNum;//保存用户输入 dlt(head,BookNum);//删除用户输入 showbook(head); cout<<"请输入您要插入的图书编号:"; cin>>BookNum; float Bookprice; cout<<"请输入您要插入的图书价格:"; cin>>Bookprice; insert(head,BookNum,Bookprice); showbook(head); return 0; }
1 下一页