我创建了一个简单的银行应用程序来询问用户是要向文件中添加银行记录还是显示所有可用记录。这两个函数分别由 write_rec() 和 read_rec() 促进。但是当函数 read_rec() 被应用时,虽然它确实打印了文件中所有可用的记录(一个文件用于存储所有记录),但由于某种原因,它打印了文件中的最后一条记录两次而不是仅仅一次。看到一切正常,然后这个问题突然冒出来,真是令人沮丧。我试图找出问题出在哪里,但对于我的生活,我就是找不到它。你们能帮我解决这个问题吗?
代码如下:
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
class account_query
{
char account_number[20];
char firstName[10];
char lastName[10];
float total_Balance;
public:
void set_data();
void show_data();
void write_rec();
void read_rec();
};
void account_query::set_data()
{
cout<<"\nEnter Account Number: ";
cin>>account_number;
cout<<"Enter First Name: ";
cin>>firstName;
cout<<"Enter Last Name: ";
cin>>lastName;
cout<<"Enter Balance: ";
cin>>total_Balance;
cout<<endl;
}
void account_query::show_data()
{
cout<<"Account Number: "<<account_number<<endl;
cout<<"First Name: "<<firstName<<endl;
cout<<"Last Name: "<<lastName<<endl;
cout<<"Current Balance: Rs. "<<total_Balance<<endl;
cout<<"-------------------------------"<<endl;
}
void account_query::write_rec()
{
ofstream outfile;
outfile.open("D:/rec.bin", ios::binary|ios::in|ios::out|ios::app);
set_data();
outfile.write(reinterpret_cast<char *>(this), sizeof(*this));
outfile.close();
}
void account_query::read_rec()
{
ifstream outfile;
outfile.open("D:/rec.bin", ios::binary);
if(!outfile.is_open())
{
cout << "Error! File not found!" << endl;
return;
}
cout << "\n****Data from file****" << endl;
while(outfile.good())
{
outfile.read(reinterpret_cast<char *>(this), sizeof(*this));
show_data();
}
outfile.close();
}
int main()
{
account_query A;
int choice;
cout << "***Account Information System***" << endl;
while(true)
{
cout << "Select one option below";
cout << "\n\t1-->Add record to file";
cout << "\n\t2-->Show record from file";
cout << "\n\t3-->Quit";
cout << "\nEnter you chice: ";
cin >> choice;
switch(choice)
{
case 1:
A.write_rec();
break;
case 2:
A.read_rec();
break;
case 3:
exit(0);
break;
default:
cout << "\nEnter correct choice";
exit(0);
}
}
system("pause");
return 0;
}
这是我尝试在控制台上打印记录时得到的结果:
请帮帮我?
答案 0 :(得分:1)
正如评论部分已经指出的那样,问题在于该行
while(outfile.good())
只会检查流提取是否已经失败。它不会告诉您下一个流提取操作是否会失败。它无法提供此信息。
因此,您必须在尝试进行流提取操作后检查流的状态,以查看它是否成功。所以你必须在这一行之后检查流状态:
outfile.read(reinterpret_cast<char *>(this), sizeof(*this));
在调用 show_data
之前应该检查它,因为如果流提取失败,您不想调用 show_data
。
最简单的解决方法是更改行
while(outfile.good())
{
outfile.read(reinterpret_cast<char *>(this), sizeof(*this));
show_data();
}
以下内容:
while( outfile.read(reinterpret_cast<char *>(this), sizeof(*this) ) )
{
show_data();
}
这会起作用,因为 istream::read
将返回对流对象 outfile
的引用并写入
while ( outfile )
相当于
while ( !outfile.fail() )
由于 istream::operator bool
被调用。