读书人

这样为什么不行啊解决方案

发布时间: 2012-04-13 13:50:24 作者: rapoo

这样为什么不行啊!
[size=24px][/size]
#include<iostream>
#include<string>
using namespace std;
class book{
public:
int BookID;
float price;
book *next;
};
book *head=NULL;
bool checki(string str)
{
for(int i=0;i<str.length ();i++)
if((str[i]>'9'||str[i]<'0'))
return false;
return true ;
}
bool checkf(string str)
{ int k=0;
for(int i=0;i<str.length ();i++)
{
if((str[i]>'9'||str[i]<'0')&&str[i]!='.')
{

return false;
}
if(str[i]=='.') k++;
}
if(k>1||str[0]=='.') return false;
return true ;
}
book *creat()
{
book *p1,*p2; //p1作为下一个节点的指针,p2作为本节点的指针
p1=new book; //新建一个节点,用p1和p2指向他,并把它当做头结点,用head指向他
head=p1;
p2=p1;
cout<<"创建节点,请输入图书编号,以0结束\n";
string str;
cin>>str;
while(!checki(str))
{
cout<<"输入的格式不正确,请重新输入\n";
cin>>str;
}
p1->BookID =atoi(str.c_str ());
if(p1->BookID ==0)
{
cout<<"您输入的头结点编号为0,退出录入\n";
delete p1;
p1=0;
head=0;
p2->next =0;
p2=0;
return head;
}
else?
{ ?
cout<<"编号不为0,请输入编号为"<<p1->BookID <<"的价格"<<endl;
cin>>str;
while(!checkf(str))
{
cout<<"输入的格式不正确,请重新输入\n";
cin>>str;
}
p1->price=atof(str.c_str ());?

}
while(p1->BookID !=0)
{
p2=p1;
p1=new book;
cout<<"请输入要录入的图书编号,输入0表示结束输入\n";
cin>>str;
while(!checki(str))
{
cout<<"输入的格式不正确,请重新输入\n";
cin>>str;
}
p1->BookID =atoi(str.c_str ());
if(p1->BookID !=0)
{
cout<<"编号不为0,请输入编号为"<<p1->BookID <<"的图书价格"<<endl;
cin>>str;
while(!checkf(str))
{
cout<<"输入的格式不正确,请重新输入\n";
cin>>str;
}
p1->price=atof(str.c_str ());?
}
p2->next =p1;
}
cout<<"您输入了0,退出录入\n";
delete p1;
p2->next =0;
return head;
}
void showbook(book *head)
{
? cout<<"图书信息如下\n";
? while(head)
? {
cout<<"编号: "<<head->BookID<<" 价格 "<<head->price<<endl;
head=head->next ;
? }
}
void deletebook(book *head,int booknum)
{
book *h;
if(head->BookID ==booknum)
{
cout<<"删除头结点\n";
h=head;
head=head->next;
::head =head;
delete h;
return ;
? }
while(head)
{
if(head->next==NULL)
{
cout<<"找不到要删除的编号\n";
return ;
}
if(head->next ->BookID ==booknum)
{
h=head->next ;
head->next=h->next ;
delete h;
cout<<"删除成功\n";
return ;
}
head=head->next ;
}
cout<<"找不到要删除的编号\n";
}
int main()
{ ?
//book *head=0; 为什么这里不能定义头结点啊!是会覆盖还是?求解答
head=creat();
showbook(head);
cout<<"请输入要删除的图书编号\n";
int booknum;
cin>>booknum;
deletebook(head,booknum);
showbook(head);
return 0;
}请看主函数中的注释!求解答



[解决办法]
book *head=NULL;
你前面是不是有同名的全局变量么?还定义局部变量干什么呢
[解决办法]
是的,而且根据你写的代码你的head只能定义为全局的。。。

读书人网 >C++

热点推荐