#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class PERSON{
string name, surname;
public:
void set_name(string aname, string asurname){
name = aname;
surname = asurname;
};
void read(){
}
void output(){
cout << name << " " << surname << "\n";
}
void save(PERSON *x){
ofstream file("test.bin", ios::out | ios::app | ios::binary);
if(!file.is_open()){
cout << "ERROR\n";
}else{
file.write((char*)x, sizeof(*x));
file.close();
}
}
};
/*
*
*
*
*/
int main(int argc, char** argv) {
PERSON * person1 = new PERSON;
PERSON * person2 = new PERSON;
person1->set_name("Amon", "Raa");
person1->save(oseba1);
ifstream file2("test.bin", ios::in | ios::binary);
if(!file2.is_open()){
cout << "Error\n";
return 0;
}
while(!file2.eof()){
file2.read((char *)person2, sizeof(*person2));
person2->output();
}
file2.close();
return 0;
}
这是我的代码......我做错了什么?我想要做的是每次将一个类保存到二进制文件的末尾,然后读取所有条目......
但每次我运行程序时,我只打印最后输入的名称
所以在第一次正确写入文件并且输出正常时运行它然后我将名称更改为其他名称,比如说 John Doe,我得到 2times John Doe 的输出
请帮助......我是一个完整的初学者;(