如何实现istream&用C ++重载?

时间:2018-01-30 13:23:44

标签: c++ struct ifstream ostream istream

我无法获取此代码来输出文件信息。我如何使用ostream重载输出?或者我必须以其他方式做到这一点?我无法理解。

哪种C ++排序算法最适合用于对信息升序进行排序?

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

1 个答案:

答案 0 :(得分:2)

以与style="height:75px"相同的方式重载操作符。例如:

style="height:0px"

然后,在循环中,您可以遍历数组并使用>>打印出每个ostream& operator<<(ostream& os, Employees& payroll) { os << payroll.employeeName << " " << payroll.employeeID << " " << payroll.rate << " " << payroll.hours << "\n"; return os; }

另外,如果您正在检查文件是否已打开,最好使用专用功能std::ifstream::is_open

为了对条目进行排序,最好使用std::sort,并为自己要排序的条件使用自定义谓词。例如,如果要按字母顺序基于Employee的名称进行排序,则可以使用以下命令:

Employees