#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; } } book *creat() { book *p1,*p2; p1=new book; head=p1; p2=p1; cout<<"请输入图书的编号,以0结束"<<endl; string str; cin>>str; while(!check(str)) { cout<<"输入的不是数字,请重新输入,按0返回"<<endl; cin>>str; } p1->num=atoi(str.c_str());//将c++字符串通过成员函数c_str()转换成c语言格式的字符串;atoi将其转换成整数 if(p1->num!=0) { cout<<"请输入图书的价格"<<endl; cin>>str; while(!check(str)) { cout<<"输入的不是数字,请重新输入,按0返回"<<endl; cin>>str; } p1->price=atof(str.c_str());//c++字符串通过成员函数c_str()转换成c语言格式的字符串;atof将其转换成浮点型 } else { delete p1;p2=NULL;p2->next=NULL;head=NULL;return head; } while(p1->num!=0) { p2=p1; p1=new book; cout<<"请输入图书的编号,以0结束"<<endl; cin>>str; while(!check(str)) { cout<<"输入的不是数字,请重新输入,按0返回"<<endl; cin>>str; } p1->num=atoi(str.c_str());//将c++字符串通过成员函数c_str()转换成c语言格式的字符串;atoi将其转换成整数 if(p1->num!=0) { cout<<"请输入图书的价格"<<endl; cin>>str; while(!check(str)) { cout<<"输入的不是数字,请重新输入,按0返回"<<endl; cin>>str; } p1->num=atoi(str.c_str());//将c++字符串通过成员函数c_str()转换成c语言格式的字符串;atoi将其转换成整数 } p2->next=p1; } delete p1; p2->next=NULL; return head; } void showbook(book*head) { cout<<"图书的信息:"<<endl; while(head) { cout<<"图书编号"<<head->num<<"\t"; cout<<"图书价格"<<head->price<<endl; head=head->next; } } void Delete(book*head,int num) { book*l; if(head->num==num) { l=head; head=head->next; ::head=head; delete l; cout<<"操作成功"<<endl; } while(head) { if(head->next==NULL) { cout<<"找不到要删除的编号"<<endl; return; } if(head->next->num==num) { l=head->next; 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; book*l; while(head) { l=head; head=head->next; } l->next=list; list->num=num; list->price=price; list->next=NULL; } int GetBookNum(book*head) { int num=0; while(head) { num++; head=head->next; } return num; } int main() { //book*head=NULL; head=creat(); showbook(head); cout<<"请输入你要删除的图书编号"<<endl; int BookNum; cin>>BookNum; Delete(head,BookNum); showbook(head); cout<<"请输入你要插入的编号"<<endl; cin>>BookNum; cout<<"请输入你要插入的价格"<<endl; float BookPrice; cin>>BookPrice; insert(head,BookNum); showbook(head); cout<<"图书数目:"<<GetBookNum(head)<<endl; return 0; }
时间: 2024-10-10 12:32:09