Automatically creating variables

Hi,

This sounds easy, but I am not sure how to go about it. Basically I want to read in some info from a txt file containing a Students name on one line followed followed by the students grades separated by commas on the next line. Then another Student followed by grades and so on with an unknown number of Students in the file. Then use the info from the txt file to create a number of Student objects equal to the number of Students in the txt file.

What I want to do is start at i = 0 and create a Student object S0; read the name & grades and assign them to S0. Create Student object S1; read the name & grades and assign them to S1. Here is my problem: How can I instantiate an object S and auto increment the the number?

For my example, the () does not represent direct assignment, but rather the value of i.

for (int i = 0; pChar != EOF (not proper syntax but I will figure it out); i++)
{
Student S(i);
StudentsFile.getline(pChar, 120);
StudnetsFile.getline(pGrades, 120);
S(i).pChar = pChar;
S(i).pGrades = pGrades;
}

I hope this makes sense. I am not worried about reading the file or the proper syntax of the exit loop condition, only how to instantiate the objects.

One additional comment. When the function exits will all of the objects I just created go out of scope and be destroyed thereby defeating the purpose?
You're looking for arrays or more specifically, for vectors.
With an array, it could look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
string pChar,grades;
const int maxStudents=100;
Student students[maxStudents]; //creates 100 students
int studentCount=0;
for (;...;studentCount++)
{
  getline(studentsFile,pChar);
  getline(studentsFile,grades);
  students[i].pChar=pChar;
  students[i].grades=grades;
}
for (int i=0;i<studentCount;i++)cout << "Student #" << i+1 << ": pChar=" << students[i].pChar
                                     << ", grades=" << students[i].grades << endl;

This has two problems: you're always creating 100 students, even if there are much less in the file. If there are more than 100, you have a big problem.
So that approach won't work. However, a vector can hold an arbitrary number of objects:
1
2
3
4
5
6
7
8
9
10
vector<Student> students; //creates an initially empty vector of students
while(...)
{
  Student s;
  getline(studentsFile,s.pChar);
  getline(studentsFile,s.grades);  
  students.push_back(s);
}
for (int i=0;i<students.size();i++)cout << "Student #" << i+1 << ": pChar=" << students[i].pChar
                                        << ", grades=" << students[i].grades << endl;

Last edited on
Thank You Athar!

I see where you are going with this. We actually have to create an Array class to hold the collection of Student objects so this helps tie it all together.
Topic archived. No new replies allowed.