作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我无法获取此代码来输出文件信息。我将如何使用 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/
我是一名优秀的程序员,十分优秀!