How to load class objects from file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ifstream fin("student.txt");
    int size; //size of students
    int count;
    fin >> size;

    int i=0;
    for(int i=0;i<2;i++)
    {
        string name, gender, phone;

        fin >> count >> name >> gender >> phone ;

        student[i].setName(name);
        student[i].setGender(gender);
        student[i].setPhoneNumber(phone);
    }


my student.txt is something like this
1
2
3
2
0 aaa male 123456
1 bbb male 345678


How to load the data inside the txt files and reput into the program as objects of classes? I tried the code above without any compilation error but it has runtime error. everything runs normally if I didn't call class member to set my data inside my vector which consists of students information.
closed account (43RGz8AR)
1
2
3
4
5
6
7
8
9
10
11
    for(int i=0;i<2;i++) // <- is this meant to be a const 2 or size?
    {
        string name, gender, phone;

        fin >> count >> name >> gender >> phone ;

       // try looking inside these methods as very thing that you've given should run fine.
        student[i].setName(name);
        student[i].setGender(gender);
        student[i].setPhoneNumber(phone);
    }


Your really not giving enough information for any one to truly pin down the error. Is your runtime error giving you any information other then just crashing?

EDIT: You also might want to check that the program is and can actually open your const file name before trying to get data from it. if(fin.fail()) { /* it failed! */}
Last edited on
it is the size that I get from the previous input, 2 is to check whether the loop is working or not,
I found that loop is working fine without calling update class members,
that means fin >> count >> name >> gender >> phone ; is working fine.

methods:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

class Student
{
    private:
    string name;
    string gender;
    string phone;

    public:
    Student(){};
    Student(string sName, string sGender);
    void setName(string nameVar);
    void setGender(string genderVar);
    void setPhoneNumber(string phoneNumVar);
    void Print();
    ~Student();

};

Student::Student(string sName, string sGender)
{
    name = sName;
    gender = sGender;
    phone = "None";
}

void Student::setName(string nameVar)
{
    name = nameVar;
}

void Student::setGender(string genderVar)

{
    gender = genderVar;
}

void Student::setPhoneNumber(string phoneNumberVar)
{
    phone = phoneNumberVar;
}


note:
1. this loadData function is in different cpp files because I'm doing seperate compilation
2. phone number is something I should get by doing my exercise, so I assigned every phone numbers to be "None".

I suppose the result of using initializer list is the same thing as the way I have assigned those values.
Last edited on
closed account (43RGz8AR)
try this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    fstream fin;
    fin.open("students.txt", ios::in);
    if(fin.fail()) {
          // throw error here
          cout << "Error: Could not open file." << endl;
          return;
    }
    int size; //size of students
    int count;
    // I'm guessing on this part so fix it how you want
    fin >> size;

    for( ; count  < size; count++) {
        string name, gender, phone;

        fin >> count >> name >> gender >> phone ;

        student[count].setName(name);
        student[count].setGender(gender);
        student[count].setPhoneNumber(phone);
    }
Last edited on
tried your code, and I noticed something,
I saw this in my console:
Error: Could not open file.
so what is the possible reason for fin fail?

my original code can fin the size of students and students' data,
it's the problem of putting back the data into objects..
The program can't find your file. Make sure you give the absolute path or that the path you give is relative to the path you run your program from.
bbgst: They are inside the same folder, isn't that sufficient?
If by "they" you meen the .exe (or working directory from which it's executing) and the save file, then yes. Also are you closing the stream after saving? Are you sure the data is in there and in the right format?
Try ifstream::is_open.

deathmoon wrote:
They are inside the same folder, isn't that sufficient?

Actually not. The directory where the executable is run can be different than the one it's executed from. If you do this, example:

1
2
3
$ ls
bin student.txt
$ bin/program

program will be executed on the bin directory, and won't find student.txt, unless you open it as "../student.txt".
closed account (DSLq5Di1)
I believe the problem you have with Xenouis code, is that he is opening "students.txt" rather than "student.txt" as in your original code.

Regarding your run time error, could we see the declaration of your student array?
Mathhead200:
yea I have all my cpps, txt and exe under the same folder.
I closed my stream after saving my data:
1
2
3
4
5
6
7
8
9
10
void saveData(vector<Student>& student,int studentSize)
{
    ofstream fout("student.txt");
    fout << studentSize << endl;
    for(int i=0;i<studentSize;++i)
    {
        fout << i << " " << student[i].getName() << " " << student[i].getGender() << " " << student[i].getPhoneNumber() << endl;
    }
    fout.close();
}

and what format do you mean?

bbgst: Thanks for your information, but I think I don't need complicated thing because this is my assignment and I want my txt not only readable in my pc but also in my lecturer's pc as well..
how to code with ifstream::is_open ?

sloppy9: Yea I found that. Used back my file name, at least I didnt show up fin.fail message, but the program still didn't loaded with any data inside my file =(
My declaration of student vector is inside my main folder:
vector<Student>student;

my loadData function is using pass by reference
vector<Student>& student
dear you should use READ & WRITE functions related to file handling... and deal with binary file format.... that is effective and fast......
closed account (DSLq5Di1)
deathmoon wrote:
My declaration of student vector is inside my main folder:
vector<Student>student;

There's the problem.. you have created an empty vector, student[0] and student[1] do not exist.

You could specify the number of elements in the student vector constructor vector<Student> student(size); and iterate over the vector as you are, or use the vector::push_back() function to insert new elements.

http://www.cplusplus.com/reference/stl/vector/push_back/
Last edited on
sloppy9: Get it! Thanks.
Suddenly forgot student should be a vector but not a dynamic array, so I forgot to push_back!
I just push back my data and everything works fine!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fstream fin;
    fin.open("student.txt", ios::in);
    if(fin.fail()) {
          // throw error here
          cout << "Error: Could not open file." << endl;
          return;
    }
    int size; //size of students
    fin >> size;

    for(int count =0; count<size; count++)
    {
        string name;
        int gender, phone,postalcode;
        int something;

        fin >> something >> name >> gender >> phone >> postalCode ;

        student.push_back(Student(name,gender,phone,postalCode));
    }

    fin.close();
or resize
1
2
fin >> size;
student.resize(size);


$ bin/program program will be executed on the . directory, and it will find student.txt
Topic archived. No new replies allowed.