Use the overloading operator << and >>

implement the operator << and >>

Page 1 of 1

1 Replies - 1195 Views - Last Post: 11 November 2010 - 07:38 AM Rate Topic: -----

#1 JohnnyBoy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 26-September 10

Use the overloading operator << and >>

Posted 11 November 2010 - 12:20 AM

Hi guys, i am new to C++.
Here is the assignment description: "overload the >> and << operators for the
Person class. Let pObj be a Person object, the overloaded >> operator will allow one to use
the following command to receive a specific value for each data member in pObj:
cin >> pObj;
The overloaded << operator on the other hand will allow one to use the following command
to print out all the data members of pObj on the screen.
cout << pObj;"


I got my code here, i am not sure my implementation for overloading << and >> is right or wrong. And I think i have to do something for the driver file main(),but i do not know how. Please give me some hints.Here is my code. I used different color for overloading the operator >> and <<:

#ifndef _PERSON_H
#define _PERSON_H

#include <iostream> 
#include <string> 
#include <iomanip> 
#include <cstdlib> 

using namespace std;

struct Date
{
      int day; 
      int month;
      int year; 
};

class Person
{
private:
      string fname; 
      string lname; 
      string ssn;  
      int age; 
      Date    birthDay; 
      double  salary;   
      double *grades;   
      int num_grades;   
	
	public:
       //constructors
       Person();
       Person(string firstname, string lastname, string the_ssn, int the_age, Date the_birthDay, double the_salary, int the_num_grades);
       
	   //overloading << and >>
	   friend ostream& operator<<(ostream& output, const Person& pObj);
	   friend istream& operator>>(istream& input, Person& pObj);
       
       //big three
	   Person(const Person & aperson); //copy constructor
       void operator=(const Person &rhs); //assigment operator
	   ~Person();//destructor
       void quick_sort(int left, int right); //sorts the grades
       
	  
       //mutator
       void setFname(string firstname);
       void setLname(string lastname);
       void setSSN(string SSN);
       void setAge(int Age);
       void setBirthDay(Date Birthday);
       void setDay(int Day);
       void setMonth(int Month);
       void setYear(int year);
       void setSalary(double Salary);
       void add_grade(double hw_grd);
       void update_grade(int i, double new_val);

	    //accessor
       string getFname();
       string getLname();
       string getSSN();
	   Date getBirthday();
       int getAge();
       int getDay();
       int getMonth();
       int getYear();
       double getSalary();
       double get_a_grade(int i);
       void print_grades();
       int get_num_grades();

};

//randomly get students' information except for name
void  init_Person(Person& person, string fname, string lname, int num_grades); 
string randomStrGen(int length);//randome string generator
int randomIntGen(int lowest, int highest);//random integer generator
double randomDoubleGen(double XMin, double XMax);//random double generator
void output(Person student[], int StudentNumber);//function to print out data

#endif 


#include "person.h"

//default constructor
Person::Person()
{
  fname = "na";
  lname = "na";
  ssn = "na";
  age = 0;
  birthDay.day = 0;
  birthDay.month = 0;
  birthDay.year = 0;
  salary = 0;
  num_grades = 0;
  grades = NULL;
}

//stores the data 
Person::Person(string firstname, string lastname, string the_ssn, int the_age, Date the_birthDay, double the_salary, int the_num_grades)
{
       fname = firstname;
       lname = lastname;
       ssn = the_ssn;
       age = the_age;
       birthDay.day = the_birthDay.day;
       birthDay.month = the_birthDay.month;
       birthDay.year = the_birthDay.year;
       salary = the_salary; 
       num_grades = the_num_grades;
       grades = NULL;    
}

//copy the student data~construct a new object as a copy of "aperson" 
Person::Person(const Person & aperson)
{
     fname = aperson.fname;
     lname = aperson.lname;
     ssn = aperson.ssn;
     age = aperson.age;
     birthDay.day = aperson.birthDay.day;
     birthDay.month = aperson.birthDay.month;
     birthDay.year = aperson.birthDay.year;
     salary = aperson.salary;
	 if(num_grades == 0)
         grades = NULL;
     else
		 grades = new double[num_grades];
         for( int i = 0; i < num_grades; i++)
         grades[i] = aperson.grades[i];
}
 
//assigment operator 
void Person::operator=(const Person &rhs)
{
     fname = rhs.fname;
     lname = rhs.lname;
     ssn = rhs.ssn;
     age = rhs.age;
     birthDay.day = rhs.birthDay.day;
     birthDay.month = rhs.birthDay.month;
     birthDay.year = rhs.birthDay.year;
     salary = rhs.birthDay.year;
     if(num_grades > 0)
		delete [] grades;
     num_grades = rhs.num_grades;  
     grades = new double[num_grades];
     for(int i = 0; i < num_grades; i++)
             grades[i] = rhs.grades[i];                
}

//destructor-return the memory
Person::~Person()
{
   if(grades != NULL)
   {
      delete [] grades;
      grades = NULL;
   }
}

//mutators 
void Person::setFname(string firstname)
{
     fname = firstname;
}

void Person::setLname(string lastname)
{
     lname = lastname;
}

void Person::setSSN(string SSN)
{
     ssn = SSN;
}

void Person::setAge(int Age)
{
     age = Age;
}

void Person::setBirthDay(Date Birthday)
{
     birthDay.day = Birthday.day;
     birthDay.month = Birthday.month;
     birthDay.year = Birthday.year;
}

void Person::setDay(int Day)
{
     birthDay.day = Day;
}

void Person::setMonth(int Month)
{
     birthDay.month = Month;
}
       
void Person::setYear(int Year)
{
     birthDay.year = Year;
}


void Person::setSalary(double Salary)
{
     salary = Salary;
}

//sets the grade
void Person::add_grade(double hw_grd)
{
	//if empty,allocate one new double
	if (num_grades == 0)
	{
		grades = new double [1];
		//verity it is scuscessful
		if(grades == NULL) {
			cerr << "Copy constructor: memory allocation error (1)!\n";
	        return;        
          }

		grades[0] = hw_grd;
	}
	else //resizing, increase the size of array by 1
	{
		double *temp_grades = new double[num_grades];
		if(temp_grades == NULL){
			cerr << "Copy constructor: memory allocation error (2)!\n";
			return;   
		   
		}
		for (int i=0; i<num_grades; i++)  //save the grades
          temp_grades[i] = grades[i];
          delete [] grades;
          grades = new double [num_grades+1]; //expand the list by one
          //verify the above allocation
          if (grades == NULL ){
          cerr << "Copy constructor: memory allocation error (3)!\n";
          return;      
          }
          for ( int i=0; i<num_grades; i++)
              grades[i] = temp_grades[i]; //copy the existing grades
          grades[num_grades] = hw_grd; // add the new grade
          delete [] temp_grades;
      }

	num_grades +=1;

}


//keep track the grades
void Person::update_grade(int i, double new_val)
{
     if(i > 0 && i <= num_grades)
	 {
          grades[i-1] = new_val;
     }
}

//prints out the grade
void Person::print_grades()
{
     if(num_grades > 0)
	 {   //setprecision(2) reduce the decimal numbers
        for( int i = 0; i < num_grades; i++){
          cout << setprecision(2) << grades[i] << " ";} 
          cout << endl;
          cout << fixed;
     }
}  

//accessors                  
string Person::getFname()
{
   return fname;
}

string Person::getLname()
{
   return lname;
}

string Person::getSSN()
{
   return ssn;
}

int Person::getAge()
{
   return age;
}

Date Person::getBirthday()
{
   return birthDay;
}

double Person::getSalary()
{
   return salary;
}

int Person::getDay()
{
   return birthDay.day;
}

int Person::getMonth()
{
   return birthDay.month;
}

int Person::getYear()
{
   return birthDay.year;
}

double Person::get_a_grade(int i)
{
   if(i>0 && i <= num_grades)
       return grades[i-1];
   else
	   return -1;
}

       
int Person::get_num_grades()
{
    return num_grades;
}


//get random information for student except for names
void  init_Person(Person& person, string fname, string lname, int num_grades)
{
      person.setFname(fname);//assign the name to the person
      person.setLname(lname);
      person.setSSN(randomStrGen(9));//assign ssn
      person.setAge(randomIntGen(15, 90));//assign age
      Date birthday;
      birthday.month = randomIntGen(1, 12);  //random month 1-12    
      birthday.day = randomIntGen(1, 31);//random day 1-31
      birthday.year = 2010 - (int)person.getAge();//get the year by age
      person.setBirthDay(birthday);
      person.setSalary(randomDoubleGen(0.0, 100000.0));//random salary in 0-100000
      for(int i = 0; i < num_grades; i++)  
	  {
          person.add_grade(randomDoubleGen(0, 100)); //randomly get grades in 0-100
      }
      person.print_grades(); //print out the grades
      person.quick_sort(0, num_grades-1); //sort the grades
}

//quick sort, sort the grades 
void Person::quick_sort(int left, int right)
{
     int i = left, j = right;
     double temp;
     double pivot;
	 pivot = grades[(left + right)/2];
     
     //partition 
     while ( i <= j){
           while (grades[i] < pivot)
                 i++;
           while (grades[j] > pivot)
                 j--;
           if( i <= j){
               temp = grades[i];
               grades[i] = grades[j];
               grades[j] = temp;
               i++;
               j--;
           }
     }
     //recursion 
     if (left < j)
        quick_sort(left, j);
     if (i < right)
        quick_sort(i, right);
	 
}
//random String function
string randomStrGen(int length)
{ 
    static string charset = "1234567890"; //set string only random in this range
    string result; 
    result.resize(length); 
    for (int i = 0; i < length; i++) //using loop to randomly get 9 letters (digits)
        result[i] = charset[rand() % charset.length()]; 
    return result; 
}

//random Integer function
int randomIntGen(int lowest, int highest)
{
    int I = lowest + rand() % (highest - lowest + 1);
    return I;
}


//random Double function
double randomDoubleGen(double XMin, double XMax)
{
   double range = XMax - XMin;
   double num = static_cast<double>(rand()) * range / static_cast<double>( RAND_MAX ) + XMin ;
   return num;
   
}


//Print out the information
void output(Person student[], int StudentNumber)
{
     for(int i = 0; i < StudentNumber; i++)
	 {
             cout << "Name:" << student[i].getFname() << " ";
             cout << student[i].getLname() << endl;
             cout << "SSN:" << student[i].getSSN() << endl;
             cout << "Age:" << student[i].getAge() << endl;
             cout << "Salary:$" <<setprecision(2) << fixed <<student[i].getSalary() << endl; 
             Date birthday;
             birthday = student[i].getBirthday();
             cout << "Date of Birth: " << (int)birthday.month << "-";
             cout << (int)birthday.day << "-"; 
             cout <<  birthday.year << endl;
             cout << "Grades:";
             student[i].print_grades();
             cout << endl;
     }
}
===========================================================
//Need help here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	 
ostream& operator<<(ostream& output,const Person& pObj)
{
	output << "Name: "<< pObj.fname<<" "<<pObj.lname <<endl;
	output << "SSN:" <<pObj.ssn << endl;
	output << "Age: " <<pObj.age << endl;
	output << "Salary:$" <<setprecision(2) << fixed <<pObj.salary << endl;
	output << "Date of birth: "<< pObj.birthDay.month << "-"; 
	
	//Date birthday;
	//birthday = pObj.birthDay;
	//output << "Date of Birth: " <<(int)birthday.month << "-";
	//output << pObj.birthday.day << "-";
	//output << pObj.birthday.year << endl;

	output << pObj.birthDay.day << "-";
	output << pObj.birthDay.year << endl;
	for (int i = 0; i <pObj.num_grades;i++)
		output << "Number Of grades" << i << " :"<<pObj.grades[i]<<endl;  
	return output; //returns a reference
}


//uses iostream and cstdlib
istream& operator>>(istream& input, Person& pObj)
{
	int NumberOfStudent;
	input >> NumberOfStudent;
	input >> pObj.fname >> pObj.lname;
	return input;
}


#include "person.h"

int main()
{
	int StudentGrades;  
	string firstname, lastname;   
	int NumberOfStudent;
    cout << "How many SFSU students?" << endl; 
    cin >> NumberOfStudent;
    Person *person;
    person = new Person[NumberOfStudent];
   
    if( NumberOfStudent >= 1)
	{
        cout<< "Please enter student's first name & last name: " << endl;
        cout << "(Separate them by space)" << endl;
        cin >> firstname >> lastname; 
		cout << "Please also enter number of grades for this student: " << endl;	
		cin	>> StudentGrades; 
        init_Person(person[0], firstname, lastname,StudentGrades);//initial first student
		cout << endl;
		//get more for more students
        for (int i = 1; i < NumberOfStudent; i++)
		{
            cout << "Please enter next student's first name & last name:\n"; 
            cin >> firstname >> lastname;
			cout << "Please also enter number of grades for this student: " << endl;
			cin >> StudentGrades;
            init_Person(person[i], firstname, lastname,StudentGrades);//initalize them
		cout << endl;
        }
    }
	cout << endl;  
    cout << "Print out the student information randomly and sorted the grades: " << endl;
	
	output(person,NumberOfStudent);//print out the information
   
    return 0;
}

This post has been edited by JohnnyBoy: 11 November 2010 - 12:23 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Use the overloading operator << and >>

#2 jimblumberg  Icon User is online

  • member icon


Reputation: 3845
  • View blog
  • Posts: 11,753
  • Joined: 25-December 09

Re: Use the overloading operator << and >>

Posted 11 November 2010 - 07:38 AM

Quote

I got my code here, i am not sure my implementation for overloading << and >> is right or wrong.


So does the code compile without error/warning messages?

If not please post the entire message.

If it compiles, what problem are you having?

What are your inputs?

What are the outputs?

What did you expect?

Quote

And I think i have to do something for the driver file main(),but i do not know how.


Did you read your instructions?

Quote

"overload the >> and << operators for the
Person class. Let pObj be a Person object, the overloaded >> operator will allow one to use
the following command to receive a specific value for each data member in pObj:
cin >> pObj;
The overloaded << operator on the other hand will allow one to use the following command
to print out all the data members of pObj on the screen.
cout << pObj;"


What part do you not understand?

Jim
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1