Writing file data into a class? C++ -


i have class looks this:

class test { public:     test() {}     ~test() {}      //i kept these public simplicity's sake @ point (stead of setters).     int first_field;     int second_field;     int third_field;     string name; }; 

my .txt file looks this:

1  2323   88   test name a1 2  23432  70   test name a2 3  123    67   test name b1 4  2332   100  test name b2 5  2141   98   test name c1 7  2133   12   test name c2 

i able read in each line file vector, current code looks this:

#include "test.h" #include <fstream> #include <iostream> #include <vector> #include <string>  using namespace std;  int main() {     ifstream file;     vector<test> test_vec;      file.open("test.txt");     if(file.fail())     {         cout << "error: cannot open file." << endl;         exit(0);     }      while(!file.eof())     {         string input;         if(file.peek() != '\n' && !file.eof())         {             test test;              file >> test.first_field >> test.second_field >> test.third_field;             getline(file, input);             test.name = input;              test_vec.push_back(test);         }     }      return 0; } 

so, i'm stuck @ portion want read in data... i've tried input stream operator , doesn't anything; other options give me errors. preserve formatting if possible. want later able sort vector different data fields in class.

any ideas?

edit: problem has been solved , code has been edited reflect it. thank help. :)

one issue should solved before reading file , parsing objects of class is:

  test test;   test.push_back(test); 

your local variable test object of class test, hides vector:

vector<test> test; 

when do:

test.push_back(test); 

you have troubles. try name object different name.

now can think how process each line, may following:

ifstream file; file.open("test.txt"); int first_field, second_field, third_field; string testname; while (!file.eof()) {    file >> first_field >> second_field >> third_field;    getline(file, testname);    cout << first_field <<" " <<  second_field << " " << third_field;    cout << endl << testname <<endl;      //you should set constructor of test accept 4 parameters     //such can create objects of test , push them vector } 

Comments