如何从文件中读入 class 个对象的向量?
How to read from file into a vector of class objects?
我需要能够保存 class 个对象的向量,我可以做到;但是,我不知道如何读回数据。我已经尝试了所有我知道如何做的事情以及我在这里看到的一些事情,none 对我有帮助。
我创建了一个测试 class 和 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;
}
如果有人能帮助我,将不胜感激。
问题出在您的 operator >>
上。当您读取 id
时,不会消耗后面的换行符,因此当您读取下一个对象时,您会读取一个空行作为其名称。修复它的一种方法是在阅读 id
:
后调用 in.ignore()
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;
in.ignore();
return in;
}
我需要能够保存 class 个对象的向量,我可以做到;但是,我不知道如何读回数据。我已经尝试了所有我知道如何做的事情以及我在这里看到的一些事情,none 对我有帮助。
我创建了一个测试 class 和 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;
}
如果有人能帮助我,将不胜感激。
问题出在您的 operator >>
上。当您读取 id
时,不会消耗后面的换行符,因此当您读取下一个对象时,您会读取一个空行作为其名称。修复它的一种方法是在阅读 id
:
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;
in.ignore();
return in;
}