【问题标题】:How to implement istream& overloading in C++?如何在 C++ 中实现 istream 和重载?
【发布时间】: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&amp; operator&lt;&lt;()
  • 取出int pay = atoi(payrollStuff);payrollStuff数组还没有初始化,那么你就永远不用pay了。如果您使用(非成员)函数std::istream&amp; std::getline(std::istream&amp;, std::string&amp;);,您将能够处理任意数量的字符。
  • 您想如何对您的条目进行排序(什么成员将作为标准)?
  • 2 个字符串变量和 2 个整数变量。按员工 ID 排序
  • fyi...声明“const int SIZE = 5” - 好...。不使用它进行任何数组大小调整或循环控制...不好

标签: c++ struct ifstream ostream istream


【解决方案1】:

只需像 &gt;&gt; 那样重载运算符即可。例如:

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

然后,在一个循环中,您可以遍历数组并使用&lt;&lt; 打印出每个Employees

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

对于您的条目进行排序,最好使用std::sort,并为您想要排序的任何标准使用自定义谓词。例如,如果您想根据 Employee 的姓名按字母顺序进行排序,您可以使用以下命令:

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

【讨论】:

  • endl 不比"\n" 好看吗?
  • 取决于你是否想要强制冲洗。
  • @WhatsUp 你总是可以创建一个 ::endl ,如果你愿意,它只是一个 "\n" ......因为你自然不会在顶部有一个 using namespace std它会使用你的 endl 而不是 std::endl。
猜你喜欢
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
  • 2010-10-03
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多