文件指针的问题?

羊城咩咩咩 2004-04-17 12:35:06
这是个根据车牌号码给出相应的客户资料的程序。
#include<iostream.h>
#include<fstream.h>
#include<string.h>
class Customer
{
private:
char name[15];
char carID[10];
public:
void get()
{
cout<<"Enter the name of the customer :"<<endl;
cin>>name;
cout<<"Enter the ID of the customer's car :"<<endl;
cin>>carID;
}
void display()
{
cout<<"The name of the customer is "<<name<<endl;
cout<<"The ID of the car is "<<carID<<endl;
}
bool compareID(char str[])
{
if(strcmp(carID,str)==0)
return true;
return false;
}
};
int main()
{
Customer custObj;
ofstream out("c:\\test.txt");
char str[10];
char choice;
//Write records to the file
cout<<"Please input the detail of the customer :"<<endl;
do
{
custObj.get();
out.write((char *)&custObj,sizeof(Customer));
cout<<"Do you want to enter more records?(y/n)"<<endl;
cin>>choice;
}while(choice!='n'&&choice!='N');
out.close();
//Read records from the file
ifstream display("c:\\test.txt");
cout<<"Do you wish to check the detail?(y/n)"<<endl;
cin>>choice;
while(choice!='n'&&choice!='N')
{
display.seekg(0,ios::beg); //当输入不存在的车牌号码时指针好象回不了头部了
display.read((char *)&custObj,sizeof(Customer));
cout<<"Please enter the car ID whose you want to check :"<<endl;
cin>>str;
//Check the detail with the ID of the car
while(display)
{
if(custObj.compareID(str))
{
custObj.display();
break;
}
display.read((char *)&custObj,sizeof(Customer));
if(!display)
{
cout<<"There is no such an ID."<<endl;
break;
}
}
cout<<"Do you wish to check again?(y/n)"<<endl;
cin>>choice;
}
display.close();
return 0;
}
当输入存在的车牌号码时,会给出相应的资料。可是输入了不存在的号码,它给出“There is no such an ID!"后,就算再输入存在的号码,也得不到资料了,
如果不用display.seekg()方法控制指针,而是通过关闭文件再打开文件的方式使指针指想文件开头,问题就可以解决。
while(choice!='n'&&choice!='N')
{
display.seekg(0,ios::beg);
display.read((char *)&custObj,sizeof(Customer));

cout<<"Please enter the car ID whose you want to check :"<<endl;
cin>>str;
//Check the detail with the ID of the car
while(display)
{
if(custObj.compareID(str))
{
custObj.display();
break;
}
display.read((char *)&custObj,sizeof(Customer));
if(!display)
{
cout<<"There is no such an ID."<<endl;
break;
}
}
cout<<"Do you wish check again?(y/n)"<<endl;
cin>>choice;
display.close(); //这里改了
display.open("c:\\test.txt");
}
display.close();
请问是什么原因?
...全文
63 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
bm1408 2004-04-17
  • 打赏
  • 举报
回复
这样一试不知如何:
display.seekg(1);

64,685

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧