此程序有效但在开头打印垃圾值(ch = 2)并打印两次相同的输出。 我正在将它用于我的项目。它包含更多数据,我使用单个对象而不是对象数组。它没有用。数组的每个对象都存储一组数据。
#include<iostream>
#include<fstream>
using namespace std;
class rw //a class containing some data
{
public:
int n;
char a;
};
int main()
{
int i;
rw r[2]; //an array of objects
int ch;
fstream f1;
f1.open("file1.txt",ios::in|ios::out|ios::ate);
cout<<"1-read,2-write";
cin>>ch;
f1.seekp(0,ios::beg);
if(ch==1)//for saving
{
r[0].n=1;
r[0].a='a';
f1.write((char*) &r[0],sizeof(r[0]));
r[1].n=2;
r[1].a='b';
f1.write((char*)&r[1],sizeof(r[1]));
}
if(ch==2)//for reading
{
f1.seekg(0,ios::beg);
while(!f1.eof())
{
i=0;
cout<<r[i].n<<r[i].a;
cout<<"\n";
f1.read((char*)&r[i],sizeof(r[i]));
i++;
}
}
system("pause");
return 0;
}
答案 0 :(得分:0)
更改以下代码
cout<<r[i].n<<r[i].a;
cout<<"\n";
f1.read((char*)&r[i],sizeof(r[i]));
到
f1.read((char*)&r[i],sizeof(r[i])); // Moved before printing
cout<<r[i].n<<r[i].a;
cout<<"\n";
您正在输出数据,然后从文件中读取,而您应该阅读然后打印。在读取之前打印是在第一次循环中获取垃圾的原因。我认为你移动了下面的阅读,以避免重复打印最后一个记录。继续阅读以了解如何避免双重阅读。
您应该避免使用while (!f1.eof())
,因为它会打印两次最后的数据。
更好地使用while(f1.read((char*)&r[i],sizeof(r[i])));
为2个输入展开eof版本的循环
while(!eof) // true
read first data
print first data
while(!eof) // true
read second data // read all, but was succesful and eof not set
print second data
while(!eof) // true
Try to read // Could not read, eof set
print data // Reprinting second data
while(!eof) // false
答案 1 :(得分:0)
不要使用while (!f1.eof())
,它将无法正常工作,因为{<1}}标志在 后尝试从超出范围内读取后才会设置文件。相反,例如, eofbit
。
还要注意这样的循环而不进行边界检查。如果文件不正确,您可能会写出数组while (f1.read(...))
的范围。