Constructors and its implementation in the program

I just need help or an explanation about the usage of constructors

Page 1 of 1

6 Replies - 1075 Views - Last Post: 25 July 2010 - 09:28 AM Rate Topic: -----

#1 Guest_crodriguez*


Reputation:

Constructors and its implementation in the program

Posted 22 July 2010 - 05:21 PM

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)

# 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.

Is This A Good Question/Topic? 0

Replies To: Constructors and its implementation in the program

#2 Guest_crodriguez*


Reputation:

Re: Constructors and its implementation in the program

Posted 22 July 2010 - 06:49 PM

To be specific, I'm having trouble mainly with the second constructor. I simple am not sure what to put in it. However, this is how the constructors look like now, give me feedback please, I'd appreciate it:

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];
     
}

Was This Post Helpful? 0

#3 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 282
  • View blog
  • Posts: 1,456
  • Joined: 16-May 09

Re: Constructors and its implementation in the program

Posted 23 July 2010 - 09:48 AM

Well, your constructor makes no sense to me:
Student::Student(int size){
    //How many grades would you like to insert?
    int grade[size];
     
    size = 3; //you get size from argument, but now you use a value of 3
    //the following assignment Can get out of bounds if the size provided in argument is <=3
    grade[size] = gptr[size];
}

Was This Post Helpful? 0
  • +
  • -

#4 Guest_crodriguez*


Reputation:

Re: Constructors and its implementation in the program

Posted 23 July 2010 - 10:43 PM

Yeah, I've managed to fix that with some help. Still having some difficulties with my program though, mainly the DisplayStudent and DisplayClass functions. Not quite sure how to get them to work. This is how my program looks as of now:

# 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);
         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;
     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;
 
    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, size); // 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[], 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;
         
         Class >> name >> last >> age >> gender >> size; 
         grade = new int[size];
         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 >> size;
             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;
     }
}      
      
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;
      
}



Any suggestions would prove very useful and I would appreciate it. If you need some clarification on something, just let me know.
Was This Post Helpful? 0

#5 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Constructors and its implementation in the program

Posted 23 July 2010 - 10:45 PM

If your program does not behave as expected, you should debug it...
Was This Post Helpful? 1
  • +
  • -

#6 Guest_crodriguez*


Reputation:

Re: Constructors and its implementation in the program

Posted 25 July 2010 - 08:20 AM

Well I was finally able to debug it and fixed errors it stated but my program still does not work well, specifically two functions. One to display the students in the class and the other to display the class summary, and I'm not sure what exactly is causing it to not work. What it does (when I choose option 3), is it keeps displaying the last name I entered repeatedly and it shows garbage for the grades. Any help would be appreciated.
Was This Post Helpful? 0

#7 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Constructors and its implementation in the program

Posted 25 July 2010 - 09:28 AM

It's probably your use of eof. I'd like you to tell me what eof() gets you.

Example from your code: while(!Class.eof()){

EDIT: After you have explained to me what you think eof does, I want you to quote documentation here.

This post has been edited by Oler1s: 25 July 2010 - 09:30 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1