Andrew B.
Andrew B.

Reputation: 167

How to read from file into a vector of class objects?

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

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.

Upvotes: 1

Views: 2582

Answers (1)

Anton Savin
Anton Savin

Reputation: 41301

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:

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

Upvotes: 2

Related Questions