【发布时间】:2018-01-30 13:23:44
【问题描述】:
我无法获取此代码来输出文件信息。我将如何使用 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<<()。 -
取出
int pay = atoi(payrollStuff);:payrollStuff数组还没有初始化,那么你就永远不用pay了。如果您使用(非成员)函数std::istream& std::getline(std::istream&, std::string&);,您将能够处理任意数量的字符。 -
您想如何对您的条目进行排序(什么成员将作为标准)?
-
2 个字符串变量和 2 个整数变量。按员工 ID 排序
-
fyi...声明“const int SIZE = 5” - 好...。不使用它进行任何数组大小调整或循环控制...不好
标签: c++ struct ifstream ostream istream