如何从文件读取类对象的向量?

时间:2023-02-05 14:06:20

I need to be able to save a vector of class objects, which I am able to do; however, I can not figure out how to read back in the data. I have tried all of the things that i know how to do and some of the things i have seen on here, none of it has helped me.

我需要能够保存一个类对象的向量,我能够做到;但是,我无法弄清楚如何读回数据。我已经尝试了所有我知道如何做的事情以及我在这里看到的一些事情,这些都没有帮助过我。

I have created a test class and main to figure out a way to read in the data. The latest attempt i was able to get the first object into the program but the rest don't. This is a test to see if i can get it to work before I implement it into my homework, that have multiple data members

我已经创建了一个测试类和main来找出一种读取数据的方法。最新的尝试我能够让第一个对象进入程序,但其余的没有。这是一个测试,看看我是否可以在我将其实现到我的家庭作业之前使其工作,这有多个数据成员

code:

码:

#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;
}

If anyone can help me it would be greatly appreciated.

如果有人可以帮助我,将不胜感激。

1 个解决方案

#1


2  

The problem is in your operator >>. When you read id, the following newline character is not consumed, so when you read the next object you read an empty line as its name. One way to fix it is to call in.ignore() after reading id:

问题在于您的运营商>>。当您读取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

Coliru演示

#1


2  

The problem is in your operator >>. When you read id, the following newline character is not consumed, so when you read the next object you read an empty line as its name. One way to fix it is to call in.ignore() after reading id:

问题在于您的运营商>>。当您读取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

Coliru演示