Dynamic arrays and files

I really need help on this one project Ive been working on for a while. basically i have a file that has:

number of students
student1 lastname
student1 firstname
student1 grade
student1 gpa
student2 lastname
student2 firstname
(ect)

and with this i am supposed to open the file, read the data, create a dynamic array to hold the data read from the file, allocate individual student objects on the heap, and sort according to what the user inputs

I am having A LOT of trouble with the project (except for opening the file) and i was wondering if you have any tips to help get me started. thanks

-bananatackle
There are many ways of doing this, but the easiest that comes to mind would be to create a simple structure:

1
2
3
4
5
6
struct student {
string lastname;
string firstname;
float grade;
float gpa;
};


you could then create a vector called, let's say cohort which contains a list of pointers to students;

1
2
3
4
5
6
7
8
9
10
vector<student*> cohort; // declare the vector

// now let's say we want to add a student to the cohort:
cohort->push_back(new student); // create a blank student

// or assuming that we have made a constructor that creates a student from a file:
cohort->push_back(new student(source_filename)); // look up class constructors for info on how to do this

// now if we want to access, say the 4th student's gpa in the list:
float gpa_of_fourth_student = cohort[3]->gpa;


remember that structures in C++ are exactly the same as classes, except that with classes member functions and objects are by default "private", so if you learn about classes all this will make more sense.

There really are many ways of solving such a problem, but this might get you started.

EDIT: just read that you wanted a dynamic array, so presumably the vector isn't what you were after. you could instead do this:

student * cohort = new student [num_students];

you won't be able to use push_back anymore, so you'd have to add students like this:

cohort[4] = new student;
Last edited on
Thanks, this helped a lot. But how do i take a line from each file and set it as a specific students info on the heap? i made this student * holdData[numOfStudents];, so im not sure why i have to make a new student but that is what i am supposed to do.

-bananatackle
Last edited on
Topic archived. No new replies allowed.