i have made a class with some private members and a public function suppose f1 to input the private members n manipulate them to be called in the main func. but when i use an fstream obj in func f1 to store the private data of the class in a file, i get an error that the fstream obj was not defined.
my question is how to store the private members of a class in a file....
thanks in adv, pls help me out
int main()
{
Student student;
vector <Student> students;
string filename, s;
unsigned index;
// Open the student grades file
cout << "Please enter the students filename> ";
getline( cin, filename );
ifstream inf( filename.c_str() );
if (!inf)
{
cout << "I could not open \"" << filename << "\"\n";
return 1;
}
// Read all students from file
while (inf >> student)
students.push_back( student );
inf.close();
// Display student names
for (unsigned n = 0; n < students.size(); n++)
cout << n << ": " << students[ n ].givenname << ' ' << students[ n ].surname << '\n';
// Select a student
cout << "\nWhich student's grades would you like to see? ";
getline( cin, s );
if (!(stringstream( s ) >> index))
{
for (index = 0; index < students.size(); index++)
if (s == students[ index ].name()) break;
}
if (index >= students.size())
{
cout << "No such student exists.\n";
return 1;
}
// Display that student
cout << students[ index ];
cout << "\nDone.\n";
return 0;
}
I tryed to run this code and i found out that when you want to see the grades for Brown Anita the grades are "100 100 90 78 100 100" and for Murphy Duncan "100 100 90 78 100 100 100 90 100".
I added a cout << student.grades.size(); at the beginning of the ">>" function and the size is "0 3 6"(each one for every time it enters the function). That means that it still has the values from the pevious entrys.
If i put a student.grades.clear(); then it works fine...
Isn't it supposed, the vector "grades", to be empty because it is a new vector object?
But vector isn't a new object. Thats the trick in this code.
Line 3: Student student;
Local object of type student. The values are never cleared, it's just re-populated manually. But never clears the grades vector from the previous entry.