【发布时间】:2015-04-28 21:59:47
【问题描述】:
我需要能够保存一个类对象的向量,我可以做到;但是,我不知道如何读回数据。我已经尝试了所有我知道该怎么做的事情以及我在这里看到的一些事情,但没有一个对我有帮助。
我创建了一个测试类和 main 来找出读取数据的方法。最近的尝试是我能够将第一个对象放入程序中,但其余的却没有。这是一个测试,看看我是否可以在我将它实施到我的作业中之前让它工作,它有多个数据成员
代码:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
class typeA
{
string name; //the name is multiple words
int id;
public:
typeA(string name, int id): name(name), id(id){}
typeA(){}
friend ostream& operator <<(ostream& out, const typeA& a)
{
out << a.name << '\n';
out << a.id << '\n';
return out;
}
friend istream& operator >>(istream& in, typeA& a)
{
getline(in, a.name); // since the name is first and last i have to use getline
in >> a.id;
return in;
}
};
int main()
{
vector<typeA> v;
int id = 1000;
fstream file("testfile.txt", ios::in);
typeA temp;
while(file >> temp)
{
v.push_back(temp);
}
vector<typeA>::iterator iter;
for(iter = v.begin(); iter != v.end(); iter++)
{
cout << *iter;
}
return 0;
}
如果有人可以帮助我,将不胜感激。
【问题讨论】:
-
Boost Serialization 非常适合。
-
你是怎么写的?
-
当您读取第二个对象时,
getline()会在您只读取a.id而不是它后面的换行符时留下一个空行。