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


i need able save vector of class objects, able do; however, can not figure out how read in data. have tried of things know how , of things have seen on here, none of has helped me.

i have created test class , main figure out way read in data. latest attempt able first object program rest don't. test see if can work before implement homework, have multiple data members

code:

#include <iostream> #include <fstream> #include <string> #include <vector> #include <iterator>  using namespace std;  class typea {     string name; //the name 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 name first , last have 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 can me appreciated.

the problem in operator >>. when read id, following newline character not consumed, when read next object read empty line name. 1 way fix call in.ignore() after reading id:

friend istream& operator >>(istream& in, typea& a) {     getline(in, a.name); // since name first , last have use getline     in >> a.id;     in.ignore();     return in; } 

coliru demo


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -