【问题标题】:How to read from file into a vector of class objects?如何从文件中读取类对象的向量?
【发布时间】: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 而不是它后面的换行符时留下一个空行。

标签: c++ file-io vector


【解决方案1】:

问题在于您的operator &gt;&gt;。当您阅读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;
}

Coliru demo

【讨论】:

  • 这行得通。当我在作业中实现它时,一些对象有多个字符串成员,我需要使用 getline 来处理,我必须在每个字符串成员之后使用 in.ingore() 还是在最后使用。
  • @AndrewB。你必须使用ignore() before getline(),如果之前的读取没有使用换行符,例如标准类型的operator&gt;&gt;
  • 谢谢。我现在知道了。如果你在 cin 后面有一个 'getline()',你必须使用 'ingore()'。
猜你喜欢
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多