我无法让此代码输出文件信息。我将如何使用 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/