Hey there, I need some help with the placement of constructors and how the second constructor would work (there's two of them). All I ask is for some explanation. These are the exact instructions: The default Constructor should build a dynamic array of size 3 for the grades. Another constructor must receive an integer specifying how many grades the student will store in the array (the size of the array).

And for now, I put that the default is 5 since I'm not quite sure how to implement the constructors and their function in my program.
Here's what I have so far:
(I apologize for the lack of documentation, I tend to do that once I'm done)

# include <iostream>
# include <iomanip>
# include <string>
# include <fstream>
using namespace std;

#ifndef STUDENT_H
#define STUDENT_H

// Class

class Student{
      private:
         string name,
                last;
         int age;
         char gender;
         int *gptr;
      public:
         Student();
         Student(int size);
         int CreateStudent();
         int StoreStudent(string, string, string, int, char, int[]);
         int DisplayStudent();
         char StudentGrade(float);
         float StudentAvg(int []);
};
#endif
// Carlo Rodriguez
// 22/3/10
// 801-08-5871
// carlo.rodriguez@uprrp.edu

// This programa creates a miniregister that allows the user
// to create classes, insert students into those classes,
// display the students records of the classes, as well as
// show the class summary.

#include "Student.h"
# include <iostream>
# include <iomanip>
# include <string>
# include <fstream>
using namespace std;

//Prototypes

bool CheckClass(string ClassName);
int CreateClass();
int DisplayClass();
void Instructions(void);
int Menu(void);

Student::Student(){
      int *gptr;                                                         
     gptr = new int grade[3];
}


int main()
{
  // Declaring variables
  int option;
  Student person;

// Este while es para que el programa siga corriendo mientras que sea escogido uno de los 5 optiones.
  while (option >= 1 || option <= 5){
        // Display instructions
        Instructions();
  
        // Display menu
        option = Menu();

        // Desplega la option escogida por el usuario
        cout << "You've chosen option: " << option << endl << endl;

        if (option == 1){ // Creates a class if it does not exist  
           CreateClass();
           }
        else if(option == 2){ // Adds a student record to a class (if it exists)
           person.CreateStudent();
           }
        else if(option == 3){ //
           person.DisplayStudent();
           }
        else if(option == 4){
           DisplayClass();  
           }
        else if(option == 5){     
           return 0;
           }

  }
} // End main

//Functions 

int DisplayClass (){
    //This function displays the summary of the class
     
     string name;  // Variable of the first name
     string last; // Variable that contains the last name
     int age; // Variable of the age
     char gender;  // Variable of the gender
     int grade[5]; // Variable of the 5 grades
     int i = 0;
     
     int gradetotal[5]={0,0,0,0,0};
     int AgeTotal;    
          
     float gradeavg[5]; // Variable used to store the average of each grade
     float AgeAvg = 0;   // Variable used to store the average age
     int male = 0;  
     int female = 0; 
    
     ifstream Class;
     string ClassName;
    
     cout << "Enter a class: " << endl;
     cin >> ClassName;
    
     ClassName.append(".dat");
     Class.open(ClassName.c_str(),fstream::in);
    
    if(!Class){
         cout << "Opening file " << ClassName << " for reading \n\n";
         cout << "The file could not be opened! " << endl;
         cout << "Possible errors: " << endl;
         cout << "The class does not exist. " << endl;
         exit(1);   // Exits program.
     }
     
         Class >> name >> last >> age >> gender >> grade[0] >> grade[1] 
         >> grade[2] >> grade[3] >> grade[4];        
         while(!Class.eof()){
            
            gradetotal[0] += grade[0];
            gradetotal[1] += grade[1];
            gradetotal[2] += grade[2];
            gradetotal[3] += grade[3];
            gradetotal[4] += grade[4]; 
                        
            AgeTotal += age;
            
            if (gender == 'M' || gender == 'm'){
               male++;
            }
            else if (gender == 'F' || gender == 'f'){
               female++;
            }
            i++; 
            
            Class >> name >> last >> age >> gender >> grade[0] >> grade[1] 
            >> grade[2] >> grade[3] >> grade[4];                  
            }
         
            gradeavg[0] = gradetotal[0]/i;
            gradeavg[1] = gradetotal[1]/i;
            gradeavg[2] = gradetotal[2]/i;
            gradeavg[3] = gradetotal[3]/i;
            gradeavg[4] = gradetotal[4]/i; 
                        
            AgeAvg = AgeTotal/i;
         
         // Displays the actual class summary
         cout << "\n";
         cout << "Exams Summary " << endl;                  
         cout << "Exam 1 Average:" << setprecision(2) << gradeavg[0] << endl;
         cout << "Exam 2 Average:" << setprecision(2) << gradeavg[1] << endl;
         cout << "Exam 3 Average:" << setprecision(2) << gradeavg[2] << endl;
         cout << "Exam 4 Average:" << setprecision(2) << gradeavg[3] << endl;
         cout << "Exam 5 Average:" << setprecision(2) << gradeavg[4] << endl << endl;
         
         cout << "Gender Summary " << endl;
         cout << "Females:" << female << endl;
         cout << "Males:" << male << endl << endl;
         
         cout << "Age Average:" << AgeAvg << "\n" << endl;

         return 0;
}
      
int Student::CreateStudent (){
    // This function allows the user to insert as many students he/she wants
    // to the class
    
  // Variables required for the function
  int age;
  string name;
  string last;
  char gender;
  int grade[5];
  int n, i;
  int students;
  Student person;
  char fullname[25];
  int Age;
  char Gender;
  int Grade;
    
    fstream Class;
    string ClassName;
    
    cout << "Enter a class: " << endl;
    cin >> ClassName;
    
    
    if (CheckClass(ClassName)==true){              
         cout << "How many students would you like to enter: " << endl;
         cin >> students;
         for (i = 0; i < students; i++){
             // Asks the user how many students he/she would like to enter
             // and for each one it asks the user to enter the student record
             cout << "Enter student information: " << endl;
             cout << "Enter first name: " << endl;
             cin >> name;
             //strcpy(name, fullname);
             cout << "Enter last name: " << endl;
             cin >> last;
             //strcpy(last, fullname);
             cout << "Enter age: " << endl;
             cin >> age;
             //age = Age;
             cout << "Enter gender: (M or F)" << endl;
             cin >> gender;
             //gender = Gender;
             cout << "Enter 5 grades: " << endl;
             cout << "Enter grade 1: " << endl;
             cin >> grade[0];
             //grade[0] = Grade;
             cout << "Enter grade 2: " << endl;
             cin >> grade[1];
             //grade[1] = Grade;
             cout << "Enter grade 3: " << endl;
             cin >> grade[2];
             //grade[2] = Grade;
             cout << "Enter grade 4: " << endl;
             cin >> grade[3];
             //grade[3] = Grade;
             cout << "Enter grade 5: " << endl;
             cin >> grade[4];
             //grade[4] = Grade;
         
         person.StoreStudent(ClassName, name, last, age, gender, grade); // Calls the function to store the student
         }
         return 0;
    }
    else {
         cout << "Class does not exist. " << endl;
         return 1;
     }
}     

int Student::StoreStudent(string ClassName, string name, string last, int age, char gender,int grade[5]){
    // This function stores the student information into the file
    
    ofstream Class;
    
    ClassName.append(".dat");
    
    Class.open(ClassName.c_str(),fstream::app);
    
    Class << name << endl;
    Class << last << endl;
    Class << age << endl;
    Class << gender << endl;
    Class << grade[0] << endl;
    Class << grade[1] << endl;
    Class << grade[2] << endl;
    Class << grade[3] << endl;
    Class << grade[4] << endl;
          
    Class.close(); 
    
}
     
int Student::DisplayStudent(){
    int age;
    string name;
    string last;
    char gender;
    int grade[5];
    float average;
    Student person;
    
    ifstream Class;
    string ClassName;
    
     cout << "Enter a class: " << endl;
    cin >> ClassName;
    
    cout << "\n";
    if (CheckClass(ClassName)==true){
         ClassName.append(".dat"); // Adds ".dat" to the file
         Class.open(ClassName.c_str(),fstream::in);
         
         Class >> name >> last >> age >> gender >> grade[0] >> grade[1] >> 
         grade[2] >> grade[3] >> grade[4];
         
         while(!Class.eof()){
             average = person.StudentAvg(grade);
             
             cout << name << " " << last << setw(10) << age << setw(5) 
             << gender << setw(5) << grade[0] << setw(5) << grade[1] << setw(5)
             << grade[2] << setw(5) << grade[3] << setw(5) << grade[4] << setw(5);
             cout.precision(2);
             cout << average;
             cout << "  " << person.StudentGrade(average) << endl;
             
             Class >> name >> last >> age >> gender >> grade[0] >> grade[1] >> 
             grade[2] >> grade[3] >> grade[4];
         }
         
         cout << "\n" << endl;
         
         Class.close(); 
         return 0;
    }
    else {
         cout << "Class does not exist. " << endl;
         return 1;
     }
}      

float Student::StudentAvg(int grade[]){
// Function to determine the average grade of the student

      int total = 0;   //variable de conteo para el promedio
      float avg; //variable para guardar el promedio
      
      for (int i = 0; i < 5; i++)
{
           
           total += grade[i];
          
}
      
      avg = total/5;
      
      return avg;
      
}

P.S. I omitted several functions from there and I appreciate any help whatsoever. For any clarification just let me know.

Recommended Answers

All 30 Replies

First this constructor :

Student::Student(){
    int *gptr; 
    gptr = new int grade[3];
}

is incorrect, it has a memory leak. You already have declared a gptr in your .h
file, so you can just delete int *gptr thats inside the default constructor.

Second I don't see the definition of Student(int size); in your program.
So give that a try. Hint, use the parameter size, and the argument for the new operator

Allright, well I fixed it a bit, but am still unsure on what to put inside the second constructor. :/ So here's what I got so far:

Student::Student(){                                                        
     gptr = new int[3];
}

Student::Student(int size){
     //How many grades would you like to insert?
     int grade[size];
     
     size = 3;
     grade[size] = gptr[size];
     
}

Take another look at your default constructor:

Student::Student(){                                                        
     gptr = new int[3];
}

In this constructor, what is the size of the array?... It's the default size of 3...
Perhaps writing it this way will make it easier to see what it is doing:

Student::Student(){                                                        
  const int DEFAULT_SIZE = 3;
  gptr = new int[DEFAULT_SIZE];
}

This constructor allows you to declare a student using a statement like this:

//declare a student using default constructor
Student defaultStudent;

Now, take that concept and apply it to the specified constructor. Keep in mind though that you need to be able to construct a student this way:

//declare a Student using specified constructor
int studentGradeCount = 8;
Student specifiedStudent(studentGradeCount);

Seeing a declaration like the specified one should give you a hint to how you should write your specified constructor. What happens to, or needs to happen with, studentGradeCount?

Student::Student(int size){
     //How many grades would you like to insert?
     int grade[size];
 
     size = 3;
     grade[size] = gptr[size];
 
}

This isn't a bad attempt, but it does not produce anything useful. I would be surprised if this didn't cause a seg fault error. The local array "grade" is irrelevant, it goes out of scope as soon as the constructor returns, you really don't need it. You need to perform a dynamic allocation (using "new") just like you did in the default constructor. But where do you get the size of the array that you need to allocate?;);)

>>This isn't a bad attempt

Yes it is. It wont even compile

@OP: as I hinted earlier, use the size parameter in the Student constructor as
an argument to the new operator. IE, your second constructor is almost the same
as the first, but instead of 3, you use the size variable thats in the constructor parameter.

Well, I've changed it a bit thanks to a buddy. Now it's like this:

Student::Student(){  
     m_size = 3;                                                      
     gptr = new float[m_size];
}

Student::Student(int size){
     //How many grades would you like to save?
     m_size = size;
     gptr = new float[size];
}

Thats wrong, you declare gptr as int *gptr , so that means, it cannot point
to float(s). Which means that when you did gptr = new float[m_size]; it should
have given you a compiler error. Change the float to an int.

Also dont forget to delete the pointer in your destructor.

Allright, I changed it.

now my problem is implementing these constructors into my functions. This is how CreateStudent function looks like now:

int Student::CreateStudent (){
    // This function allows the user to insert as many students he/she wants
    // to the class
    
  // Variables required for the function
  int age;
  string name;
  string last;
  char gender;
  int size;
  int grade[size];
  int j, i;
  int students;
  Student person;
  //char fullname[25];
  int Age;
  char Gender;
  int Grade;
    
    fstream Class;
    string ClassName;
    
    cout << "Enter a class: " << endl;
    cin >> ClassName;
    
    
    if (CheckClass(ClassName)==true){              
         cout << "How many students would you like to enter: " << endl;
         cin >> students;
         
         for (i = 0; i < students; i++){
             // Asks the user how many students he/she would like to enter
             // and for each one it asks the user to enter the student record
             cout << "Enter student information: " << endl;
             cout << "Enter first name: " << endl;
             cin >> name;
             cout << "Enter last name: " << endl;
             cin >> last;
             cout << "Enter age: " << endl;
             cin >> age;
             cout << "Enter gender: (M or F)" << endl;
             cin >> gender;
             cout << "How many grades would you like to enter? " << endl;
             cin >> size;
             Student Student(size);
             cout << "Now enter " << size << "grades:" << endl;
             for (j = 0; j < size; j++){
                 cout << "Enter grade " << j + 1 << ": " << endl;
                 cin >> grade[j];
             }    
         
         person.StoreStudent(ClassName, name, last, age, gender, grade); // Calls the function to store the student
         }
         return 0;
    }
    else {
         cout << "Class does not exist. " << endl;
         return 1;
     }
}

One big problem:

// Variables required for the function
...and all the code that follows...

All those variables you declare are not initialized to any value, this can be dangerous and I would suspect (or know) that your compiler is probably complaining a lot when you attempt or succeed to compile. One case of this being wrong for good reason:

int size;
  int grade[size];

First of all this will not compile because "size is not a constant expression" (this will be the compiler error). And second, it's a logic fault in the sense that what this mean is you have a variable called "size" which has no value and then you _try_ to allocate an array "grade" of that size which is undefined, it could be 0 or 734912423 or anything, that's a second reason why a compiler will object to compiling this code.

So to fix that, you need to declare "grade" as a pointer (initialized to NULL) and allocate dynamically (with new) the array of grades, once "size" is known, like you do in the constructors. All the other variables declared there should be initialized even if the initial value is a dummy value, that's not absolutely necessary, that's just good programming practice. Also, consider moving the declarations of the variables closer to where they are used, it's less confusing, more efficient, and less chance of name-mangling.

Hmm, allright well I have it like this in CreateStudent function now:

int Student::CreateStudent (){
    // This function allows the user to insert as many students he/she wants
    // to the class
    
  // Variables required for the function
  int age;
  string name;
  string last;
  char gender;
  int size;
  int *grade;
  int j, i;
  int students;
  Student person;
  //char fullname[25];
  int Age;
  char Gender;
  int Grade;
    
    fstream Class;
    string ClassName;
    
    cout << "Enter a class: " << endl;
    cin >> ClassName;
    
    
    if (CheckClass(ClassName)==true){              
         cout << "How many students would you like to enter: " << endl;
         cin >> students;
         
         for (i = 0; i < students; i++){
             // Asks the user how many students he/she would like to enter
             // and for each one it asks the user to enter the student record
             cout << "Enter student information: " << endl;
             cout << "Enter first name: " << endl;
             cin >> name;
             cout << "Enter last name: " << endl;
             cin >> last;
             cout << "Enter age: " << endl;
             cin >> age;
             cout << "Enter gender: (M or F)" << endl;
             cin >> gender;
             cout << "How many grades would you like to enter? " << endl;
             cin >> size;
             Student Student(size);
             grade = new int[size];
             cout << "Now enter " << size << " grades:" << endl;
             for (j = 0; j < size; j++){
                 cout << "Enter grade " << j + 1 << ": " << endl;
                 cin >> grade[j];
             }    
         
         person.StoreStudent(ClassName, name, last, age, gender, grade); // Calls the function to store the student
         }
         return 0;
    }
    else {
         cout << "Class does not exist. " << endl;
         return 1;
     }
}

Something like that?

Sure that works.. doesn't it? Compile, run, and see!

Well, I tried it, but unfortunately, the program stops running right after I enter the grades (the actual grades, not the amount of grades)

In your StoreStudent method, you open the file with:

Class.open(ClassName.c_str(),fstream::app);
//But it should be:
Class.open(ClassName.c_str(),fstream::app | fstream::out);

This is because only setting the opening method as "app" for append, will (weirdly enough) not set it up for either reading ("in") or writing ("out") so your file writing operations will fail. NOTE I may be wrong on this, but that's what I can see as wrong.

:/ Still same thing happens

Well... I have copy-pasted your code.. and its working fine on my side. There are a few issues with computing the average grade (you have fixed the number of grades to 5 in there), but otherwise its working. So it has to be some code that you did not post because I filled a few gaps of the not-posted code and it works fine.

Here is the console print:
Choose an option:2
You've chosen option: 2

Enter a class:
firstgrade
How many students would you like to enter:
2
Enter student information:
Enter first name:
bob
Enter last name:
gibbs
Enter age:
8
Enter gender: (M or F)
M
How many grades would you like to enter?
4
Now enter 4 grades:
Enter grade 1:
80
Enter grade 2:
75
Enter grade 3:
65
Enter grade 4:
90
Enter student information:
Enter first name:
mindy
Enter last name:
singer
Enter age:
9
Enter gender: (M or F)
F
How many grades would you like to enter?
4
Now enter 4 grades:
Enter grade 1:
70
Enter grade 2:
68
Enter grade 3:
95
Enter grade 4:
87
Choose an option:3
You've chosen option: 3

Enter a class:
firstgrade

bob gibbs 8 M 80 75 65 90 0 62 A
mindy singer 9 F 70 68 95 87 0 64 A


Choose an option:5
You've chosen option: 5

Well , I've changed my whole program a bit since the last one shown. So maybe it was something I added that is messing it up. I know that I have to fix the DisplayStudent and DisplayClass a bit yet, but I don't know why my CreateStudent functions isn't working properly (for me at least). This is my latest update of my program:

# include <iostream>
# include <iomanip>
# include <string>
# include <fstream>
using namespace std;

#ifndef STUDENT_H
#define STUDENT_H

// Class

class Student{
      private:
         string name,
                last;
         int age;
         char gender;
         int m_size;
         int *gptr;
      public:
         Student();
         Student(int size);
         ~Student();
         
         int CreateStudent();
         int StoreStudent(string, string, string, int, char, int[]);
         int DisplayStudent();
         char StudentGrade(float);
         float StudentAvg(int []);
};
#endif
// Carlo Rodriguez
// 22/3/10
// 801-08-5871
// carlo.rodriguez@uprrp.edu

// This programa creates a miniregister that allows the user
// to create classes, insert students into those classes,
// display the students records of the classes, as well as
// show the class summary.

#include "Student.h"
# include <iostream>
# include <iomanip>
# include <string>
# include <fstream>
using namespace std;

//Prototypes

bool CheckClass(string ClassName);
int CreateClass();
int DisplayClass();
void Instructions(void);
int Menu(void);

Student::Student(){  
     m_size = 3;                                                      
     gptr = new int[3];
}

Student::Student(int size){
     //How many grades would you like to save?
     m_size = size;
     gptr = new int[size];
}

Student::~Student(){
	delete[] gptr;
}


int main()
{
  // Declaring variables
  int option;
  Student person;

// Este while es para que el programa siga corriendo mientras que sea escogido uno de los 5 optiones.
  while (option >= 1 || option <= 5){
        // Display instructions
        Instructions();
  
        // Display menu
        option = Menu();

        // Desplega la option escogida por el usuario
        cout << "You've chosen option: " << option << endl << endl;

        if (option == 1){ // Creates a class if it does not exist  
           CreateClass();
           }
        else if(option == 2){ // Adds a student record to a class (if it exists)
           person.CreateStudent();
           }
        else if(option == 3){ //
           person.DisplayStudent();
           }
        else if(option == 4){
           DisplayClass();  
           }
        else if(option == 5){     
           return 0;
           }

  }
} // End main

//Functions

void Instructions(){
cout << "This program allows the user to create a class and input student records. \n" << endl;
}

int Menu(){

  int option;

  cout << "Menu:" << endl;
 
cout << "\t1) Create Class" << endl;
cout << "\t2) Insert Student Record" << endl;
cout << "\t3) Display Class Students" << endl;
cout << "\t4) Display Class Summary" << endl;
cout << "\t5) Exit Program \n" << endl;
   
     cout << "Choose an option from the Menu: " << endl;
     cin >> option;
     while ((option < 1) || (option > 5)){
                 cout << "Error: Choose between the options 1-5: " << endl;
                 cin >> option;
                 }
     
     return option;
}

bool CheckClass(string ClassName){
// This function verifies to see whether the class exists or not

    fstream Class;
    ClassName.append(".dat");
     
    Class.open(ClassName.c_str(),fstream::in);
    if (Class.good()){
        Class.close();
        return true ;
    }
    return false;
}    

int CreateClass (){
    // This function creates a file for the class entered
    
     fstream Class;
     string ClassName;
  
     cout << "Enter a class: " << endl;
     cin >> ClassName;
     
     if (CheckClass(ClassName)==false)
     {
        ClassName.append(".dat"); // Adds ".dat" to the file
    
        Class.open(ClassName.c_str(),fstream::out);
    
        cout << "The class " << ClassName << " was created" << endl;
    
         Class.close();    
         return 0;
    }
    else
    {
         cout << "The class already exists." << endl;
         return 1;
    }
}



int DisplayClass (){
    //This function displays the summary of the class
     
     string name;  // Variable of the first name
     string last; // Variable that contains the last name
     int age; // Variable of the age
     char gender;  // Variable of the gender
     int size; 
     int grade[size];
     int i, k;
     
     int gradetotal[size]; //={0,0,0,0,0};
     int AgeTotal;    
          
     float gradeavg[size]; // Variable used to store the average of each grade
     float AgeAvg = 0;   // Variable used to store the average age
     int male = 0;  
     int female = 0; 
    
     ifstream Class;
     string ClassName;
    
     cout << "Enter a class: " << endl;
     cin >> ClassName;
    
     ClassName.append(".dat");
     Class.open(ClassName.c_str(),fstream::in);
    
    if(!Class){
         cout << "Opening file " << ClassName << " for reading \n\n";
         cout << "The file could not be opened! " << endl;
         cout << "Possible errors: " << endl;
         cout << "The class does not exist. " << endl;
         exit(1);   // Exits program.
     }
     
         Class >> name >> last >> age >> gender >> grade[0] >> grade[1] 
         >> grade[2] >> grade[3] >> grade[4];        
         while(!Class.eof()){
            
         
            gradetotal[0] += grade[0];
            gradetotal[1] += grade[1];
            gradetotal[2] += grade[2];
            gradetotal[3] += grade[3];
            gradetotal[4] += grade[4]; 
                        
            AgeTotal += age;
            
            if (gender == 'M' || gender == 'm'){
               male++;
            }
            else if (gender == 'F' || gender == 'f'){
               female++;
            }
            i++; 
            
            Class >> name >> last >> age >> gender >> grade[0] >> grade[1] 
            >> grade[2] >> grade[3] >> grade[4];                  
            }
         
            gradeavg[0] = gradetotal[0]/i;
            gradeavg[1] = gradetotal[1]/i;
            gradeavg[2] = gradetotal[2]/i;
            gradeavg[3] = gradetotal[3]/i;
            gradeavg[4] = gradetotal[4]/i; 
                        
            AgeAvg = AgeTotal/i;
         
         // Displays the actual class summary
         cout << "\n";
         cout << "Exams Summary " << endl; 
         
         for(int j = 0; j < size; j++){                 
                 cout << "Exam " << j << "Average:" << setprecision(2) 
                 << gradeavg[j] << endl;
         }
         
         
         cout << "Gender Summary " << endl;
         cout << "Females:" << female << endl;
         cout << "Males:" << male << endl << endl;
         
         cout << "Age Average:" << AgeAvg << "\n" << endl;

         return 0;
}
      
int Student::CreateStudent (){
    // This function allows the user to insert as many students he/she wants
    // to the class
    
  // Variables required for the function
  int age;
  string name;
  string last;
  char gender;
  int size;
  int *grade;
  int j, i;
  int students;
  Student person;
  //char fullname[25];
  int Age;
  char Gender;
  int Grade;
    
    fstream Class;
    string ClassName;
    
    cout << "Enter a class: " << endl;
    cin >> ClassName;
    
    
    if (CheckClass(ClassName)==true){              
         cout << "How many students would you like to enter: " << endl;
         cin >> students;
         
         for (i = 0; i < students; i++){
             // Asks the user how many students he/she would like to enter
             // and for each one it asks the user to enter the student record
             cout << "Enter student information: " << endl;
             cout << "Enter first name: " << endl;
             cin >> name;
             cout << "Enter last name: " << endl;
             cin >> last;
             cout << "Enter age: " << endl;
             cin >> age;
             cout << "Enter gender: (M or F)" << endl;
             cin >> gender;
             cout << "How many grades would you like to enter? " << endl;
             cin >> size;
             Student Student(size);
             grade = new int[size];
             cout << "Now enter " << size << " grades:" << endl;
             for (j = 0; j < size; j++){
                 cout << "Enter grade " << j + 1 << ": " << endl;
                 cin >> grade[j];
             }    
         
         person.StoreStudent(ClassName, name, last, age, gender, grade); // Calls the function to store the student
         }
         return 0;
    }
    else {
         cout << "Class does not exist. " << endl;
         return 1;
     }
}     

int Student::StoreStudent(string ClassName, string name, string last, int age, char gender,int grade[]){
    // This function stores the student information into the file
    int size;
    
    ofstream Class;
    
    ClassName.append(".dat");
    
    Class.open(ClassName.c_str(),fstream::app | fstream::out);
    
    Class << name << endl;
    Class << last << endl;
    Class << age << endl;
    Class << gender << endl;
    for(int i = 0; i < size; i++){
            Class << grade[i] << endl;
    }
          
    Class.close(); 
    
}
     
int Student::DisplayStudent(){
    int age;
    string name;
    string last;
    char gender;
    int size;
    int grade[size];
    float average;
    Student person;
    
    ifstream Class;
    string ClassName;
    
     cout << "Enter a class: " << endl;
    cin >> ClassName;
    
    cout << "\n";
    if (CheckClass(ClassName)==true){
         ClassName.append(".dat"); // Adds ".dat" to the file
         Class.open(ClassName.c_str(),fstream::in);
         
         Class >> name >> last >> age >> gender >> grade[0] >> grade[1] >> 
         grade[2] >> grade[3] >> grade[4];
         
         while(!Class.eof()){
             average = person.StudentAvg(grade);
             
             cout << name << " " << last << setw(10) << age << setw(5) 
             << gender << setw(5) << grade[0] << setw(5) << grade[1] << setw(5)
             << grade[2] << setw(5) << grade[3] << setw(5) << grade[4] << setw(5);
             cout.precision(2);
             cout << average;
             cout << "  " << person.StudentGrade(average) << endl;
             
             Class >> name >> last >> age >> gender >> grade[0] >> grade[1] >> 
             grade[2] >> grade[3] >> grade[4];
         }
         
         cout << "\n" << endl;
         
         Class.close(); 
         return 0;
    }
    else {
         cout << "Class does not exist. " << endl;
         return 1;
     }
}      
      
char Student::StudentGrade(float avg)
{
// This function determines the letter grade
// of a student based on the average

     char lettergrade; // Variable used to store the corresponding letter grade
     if (avg >= 90)
	     lettergrade = 'A';
	  else if (avg >= 80)
	     lettergrade = 'B';
	  else if (avg >= 70)
	    lettergrade = 'C';
	  else if (avg >= 60)
	     lettergrade = 'D';
      else 
         lettergrade = 'F';
    
      return lettergrade;
}

float Student::StudentAvg(int grade[]){
// Function to determine the average grade of the student

      int total = 0;   //variable de conteo para el promedio
      float avg; //variable para guardar el promedio
      
      for (int i = 0; i < 5; i++)
{
           
           total += grade[i];
          
}
      
      avg = total/5;
      
      return avg;
      
}

I appreciate your help mike.

I changed one line of code:

int Student::StoreStudent(string ClassName, string name, string last, int age, char gender,int grade[]){
    // This function stores the student information into the file
    int size = 5; //added the "= 5" here, and it works (for 5 grades only, of course).

"size" was undefined before and you used it without initializing it, so your program was doing weird things. Now it will work except for the class summary which has a few integer division issues and stuff. But, of course, you need to make changes such that it works better for a number of grades different from 5. But by starting with this working version, incrementally make things work for other than 5 and run often and it should go smoothly.

Also, a tip, compile your program with the flag -Wall, this will help catching those mistakes. As in:
> g++ test.cpp -o test -Wall
test.cpp: In function ‘int DisplayClass()’:
test.cpp:187: warning: unused variable ‘k’
test.cpp: In member function ‘int Student::CreateStudent()’:
test.cpp:281: warning: unused variable ‘Age’
test.cpp:282: warning: unused variable ‘Gender’
test.cpp:283: warning: unused variable ‘Grade’
test.cpp: In member function ‘int Student::StoreStudent(std::string, std::string, std::string, int, char, int*)’:
test.cpp:348: warning: no return statement in function returning non-void
test.cpp: In function ‘int DisplayClass()’:
test.cpp:186: warning: ‘size’ may be used uninitialized in this function
test.cpp: In member function ‘int Student::DisplayStudent()’:
test.cpp:356: warning: ‘size’ may be used uninitialized in this function

Thanks mate, what I did was add size to the parameter of StoreStudent and it seems to be working fine now. Now I gotta fix the other two functions. And thanks for the tip as well, will prove useful in the future.

Hey, I haven't been able to figure out how to successfully display the students nor class.

These are my two functions:

int Student::DisplayStudent(){
    int age;
    string name;
    string last;
    char gender;
    int size;
    int grade[size];
    float average;
    Student person;
    
    ifstream Class;
    string ClassName;
    
     cout << "Enter a class: " << endl;
    cin >> ClassName;
    
    cout << "\n";
    if (CheckClass(ClassName)==true){
         ClassName.append(".dat"); // Adds ".dat" to the file
         Class.open(ClassName.c_str(),fstream::in);
         
         Class >> name >> last >> age >> gender; 
         for (int i = 0; i < size; i++){
             Class >> grade[i];
         }
         
         while(!Class.eof()){
             average = person.StudentAvg(grade);
             
             cout << name << " " << last << setw(10) << age << setw(5) 
             << gender << setw(5); 
             for (int j = 0; j < size; j++){
                 cout << grade[j] << setw(5);
             }
             cout.precision(2);
             cout << average;
             cout << "  " << person.StudentGrade(average) << endl;
             
             Class >> name >> last >> age >> gender;
             for (int k = 0; k < size; k++){
                 Class >> grade[k];
             }
         }
         
         cout << "\n" << endl;
         
         Class.close(); 
         return 0;
    }
    else {
         cout << "Class does not exist. " << endl;
         return 1;
     }
}

int DisplayClass (){
    //This function displays the summary of the class
     
     string name;  // Variable of the first name
     string last; // Variable that contains the last name
     int age; // Variable of the age
     char gender;  // Variable of the gender
     int size; 
     int grade[size];
     int i, k;
     
     int gradetotal[size]; //={0,0,0,0,0};
     int AgeTotal;    
          
     float gradeavg[size]; // Variable used to store the average of each grade
     float AgeAvg = 0;   // Variable used to store the average age
     int male = 0;  
     int female = 0; 
    
     ifstream Class;
     string ClassName;
    
     cout << "Enter a class: " << endl;
     cin >> ClassName;
    
     ClassName.append(".dat");
     Class.open(ClassName.c_str(),fstream::in);
    
    if(!Class){
         cout << "Opening file " << ClassName << " for reading \n\n";
         cout << "The file could not be opened! " << endl;
         cout << "Possible errors: " << endl;
         cout << "The class does not exist. " << endl;
         exit(1);   // Exits program.
     }
     
         Class >> name >> last >> age >> gender >> grade[0] >> grade[1] 
         >> grade[2] >> grade[3] >> grade[4];        
         while(!Class.eof()){
            
         
            gradetotal[0] += grade[0];
            gradetotal[1] += grade[1];
            gradetotal[2] += grade[2];
            gradetotal[3] += grade[3];
            gradetotal[4] += grade[4]; 
                        
            AgeTotal += age;
            
            if (gender == 'M' || gender == 'm'){
               male++;
            }
            else if (gender == 'F' || gender == 'f'){
               female++;
            }
            i++; 
            
            Class >> name >> last >> age >> gender >> grade[0] >> grade[1] 
            >> grade[2] >> grade[3] >> grade[4];                  
            }
         
            gradeavg[0] = gradetotal[0]/i;
            gradeavg[1] = gradetotal[1]/i;
            gradeavg[2] = gradetotal[2]/i;
            gradeavg[3] = gradetotal[3]/i;
            gradeavg[4] = gradetotal[4]/i; 
                        
            AgeAvg = AgeTotal/i;
         
         // Displays the actual class summary
         cout << "\n";
         cout << "Exams Summary " << endl; 
         
         for(int j = 0; j < size; j++){                 
                 cout << "Exam " << j << "Average:" << setprecision(2) 
                 << gradeavg[j] << endl;
         }
         
         
         cout << "Gender Summary " << endl;
         cout << "Females:" << female << endl;
         cout << "Males:" << male << endl << endl;
         
         cout << "Age Average:" << AgeAvg << "\n" << endl;

         return 0;
}

Any help would be appreciated.

This is an old version of your code, this will not compile. Again you have "uninitialized variables", like you had before, that you cleaned up but now you put them back in. In both functions you have:

int size;        //BIG ERROR! size = random-non-sense and is not a constant.
 int grade[size]; //BIG ERROR! grade is allocated to some random size.

If your compiler is compiling this, get a new one, because no compiler should accept this to be compiled.

Revert back to the code of your previous post, with the one line change I made and start from there. These two functions are not the same as before. Be diligent and keep track of your changes. And solve the warnings you get when compiling with -Wall.

Yeah, I know, but I'm not quite sure how to get the size I input in option 2 to the DisplayStudent (or DisplayClass) function so it can be used.

Oh, you're right. Well, save it in the file, just before listing the grades. So in CreateStudent, save "size" just before all the "grade" elements. Then in both DisplayStudent and DisplayClass, all you need to do is read "size" from the input file, then allocate the required array in "grade", and read the individual grades.
Or, if size should be the same for all students in a class, then you can save it at the very start of the file.

Just that, I thought that's what the StoreStudent function was for; to store the student's record and write it on the file.

Oh sorry when I said CreateStudent, I meant StoreStudent. my bad.

Now all it produces is a bunch of 0's. Right now, I'm just testing it with DisplayStudent and this is what I put so far:

int Student::StoreStudent(string ClassName, string name, string last, int age, char gender,int grade[], int size){
    // This function stores the student information into the file
    
    ofstream Class;
    
    ClassName.append(".dat");
    
    Class.open(ClassName.c_str(),fstream::app | fstream::out);
    
    Class << name << endl;
    Class << last << endl;
    Class << age << endl;
    Class << gender << endl;
    Class << size << endl;
    Class << grade << endl;
    for(int i = 0; i < size; i++){
            Class << grade[i] << endl;
    }
          
    Class.close(); 
    
}
     
int Student::DisplayStudent(){
    int age;
    string name;
    string last;
    char gender;
    int size;
    int *grade;
    float average;
    Student person;
    
    ifstream Class;
    string ClassName;
    
     cout << "Enter a class: " << endl;
    cin >> ClassName;
    
    cout << "\n";
    if (CheckClass(ClassName)==true){
         ClassName.append(".dat"); // Adds ".dat" to the file
         Class.open(ClassName.c_str(),fstream::in);
         
         //Class >> size;
         
         grade = new int[size];
         
         Class >> name >> last >> age >> gender; 
         for (int i = 0; i < size; i++){
             Class >> grade[i];
         }
         
         while(!Class.eof()){
             average = person.StudentAvg(grade);
             
             cout << name << " " << last << setw(10) << age << setw(5) 
             << gender << setw(5); 
             for (int j = 0; j < size; j++){
                 cout << grade[j] << setw(5);
             }
             cout.precision(2);
             cout << average;
             cout << "  " << person.StudentGrade(average) << endl;
             
             Class >> name >> last >> age >> gender;
             for (int k = 0; k < size; k++){
                 Class >> grade[k];
             }
         }
         
         cout << "\n" << endl;
         
         Class.close(); 
         return 0;
    }
    else {
         cout << "Class does not exist. " << endl;
         return 1;
     }
}
//replace this:
         grade = new int[size];
         
         Class >> name >> last >> age >> gender; 

//with that:
         Class >> name >> last >> age >> gender >> size;

         grade = new int[size];

Okay, a little bit better, now it keeps repeating the first student you inserted and displays garbage for grades

You did add ">> size" for line 66 as well, right?

Check your .dat file to make sure the students were properly saved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.