Our teacher gave us a programming assignment that is supposed to manage a students information from a text file that will be inputted that contains information of several students. We are supposed to use structures in this program and since the number of students is unknown until runtime we are supposed to use dynamic memory allocation.
Anyways my problem is right at the beginning of the program (part in bold) assignment one of the first things my teacher says to do it to:
1.Read how many students are in the file and dynamically create an array of structure to store the student information. I kind of understand how to dynamically allocate an array, and I kind of understand how to define array of structures, but I do not understand how to combine the 2 into what he is asking. Here is what I have to far:
CODE
#include <iostream>
#include <fstream>
using namespace std;
struct studentstructure
{
int studentid;
char firstname[31];
char lastname[31];
char studentmajor[11];
float gpa;
}
main (int argc, char *argv[])
{
int numstudents; // Number of student records in the file
ifstream infile;
infile.open(argv[1]);
if(!infile) // Will tell user if the path name or file is incorrect
{
cout << "Incorrect file or path name." << endl;
return 0;
}
infile >> numstudents;
if (numstudents <= 0) // Tests to make sure there are records in the file based on the very first number
// otherwise end the program
{
cout << "File contains no student records." << endl;
return 0;
}
// If there are records than continue and dynamically allocate an array of structures. This is where I'm confused
struct *students;
students = &studentstructure;
*students = new struct[numstudents];
studentstructure students[numstudents];
return 0;
}
I know this probably looks really dumb so far but I'm really confused on how to dynamically allocate an array of structures.
Btw the data file that is inputted basically, the very first number will be the number of student records and everything after that is student information, so that is why I have the numstudents variable so it stores that number.