Search code examples
c++structifstreamostreamistream

How to implement istream& overloading in C++?


I can't get this code to output the file info. How would I use ostream overloading to output this? Or do I have to do it some other way? I can't figure it out.

Which C++ sorting algorithm would be the best to use to sort the info ascending order?

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdlib.h> // needed to use atoi function to convert strings to integer

using namespace std;

struct Employees
{
   string employeeName;
   string employeeID;
   int rate;
   int hours;
};

istream& operator >> (istream& is, Employees& payroll)
{
    char payrollStuff[256];
    int pay = atoi(payrollStuff); // use atoi function to convert string to int

    is.getline(payrollStuff, sizeof(payrollStuff));
    payroll.employeeName = payrollStuff;

    is.getline(payrollStuff, sizeof(payrollStuff));
    payroll.employeeID = payrollStuff;

    is.getline(payrollStuff, sizeof(payrollStuff));
    payroll.rate = atoi(payrollStuff);

    is.getline(payrollStuff, sizeof(payrollStuff));
    payroll.hours = atoi(payrollStuff);

    return is;

};

int main()
{
    const int SIZE = 5; // declare a constant
    Employees payroll_size[5];

    ifstream myFile;
    myFile.open("Project3.dat");
    if(myFile.fail())            //is it ok?
   {
       cerr << "Input file did not open please check it" << endl;
   }
   else
   for (int i=0; i< 5; i++)
   {
       myFile >> payroll_size[i];
   }


   myFile.close();

   return 0;
}

Solution

  • Just overload the operator in the same way you did for the >>. For example:

    ostream& operator<<(ostream& os, Employees& payroll)
    {
        os << payroll.employeeName << " " << payroll.employeeID << " " << payroll.rate << " " << payroll.hours << "\n";
        return os;
    }
    

    Then, in a loop, you can just iterate over the array and print out each of the Employees using <<.

    On a side note, if you are checking if the file opened, it is better to use the dedicated function std::ifstream::is_open.

    For sorting your entries, it is best that you use std::sort, with a custom predicate for whatever criteria you want to sort with. As an example, if you wanted to sort based on the name of the Employee in alphabetical order, you would use the following command:

    sort(payroll_size, payroll_size + 5, [](const Employee& a, const Employee& b) { return a.employeeName < b. employeeName; });