gpt4 book ai didi

c++ - 如何在C++中实现istream&重载?

转载 作者:搜寻专家 更新时间:2023-10-31 02:07:32 24 4
gpt4 key购买 nike

我无法获取此代码来输出文件信息。我将如何使用 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;
}

最佳答案

只需按照对 >> 所做的相同方式重载运算符即可.例如:

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

然后,在循环中,您可以遍历数组并打印出每个 Employees使用 << .

附带说明一下,如果您要检查文件是否打开,最好使用专用函数 std::ifstream::is_open .

为了对条目进行排序,最好使用 std::sort ,对于您想要排序的任何标准都有一个自定义谓词。例如,如果您希望根据员工姓名的字母顺序进行排序,您可以使用以下命令:

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

关于c++ - 如何在C++中实现istream&重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48522510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com