如何使用文件 I/O c++

How to use file I/O c++

本文关键字:c++ 何使用 文件      更新时间:2023-10-16

首先我正在尝试创建一个文件并写入它,它不允许我使用"<<"写入文件,第二部分我试图从文件中读取数据,但我不确定这是正确的方法,因为我想将数据保存到对象中,以便以后可以在程序中使用这些对象。任何帮助或建议将不胜感激。提前致谢

void Employee::writeData(ofstream&)
{
  Employee joe(37," ""Joe Brown"," ""123 Main ST"," ""123-6788", 45, 10.00);
  Employee sam(21,"nSam Jones", "n 45 East State", "n661-9000",30,12.00);
  Employee mary(15, "nMary Smith","n12 High Street","n401-8900",40, 15.00);
  ofstream outputStream;
  outputStream.open("theDatafile.txt");
  outputStream << joe << endl << sam << endl << mary << endl;
  //it says that no operator "<<"matches this operands, operands types are std::ofstream<<employee
  outputStream.close();
  cout<<"The file has been created"<<endl;
}
void Employee::readData(ifstream&)
{
  //here im trying to open the file created and read the data from it, but I'm strugguling to figure out how to read the data and save it into de class objects.
  string joe;
  string sam;
  string mary;
  ifstream inputStream;
  inputStream.open("theDatafile.txt");
  getline(inputStream, joe);
  getline(inputStream, sam);
  getline(inputStream, mary);
  inputStream.close();
}

您收到的错误是因为您需要为雇员类定义输出运算符。

ostream& operator<<(ostream& _os, const Employee& _e) {
  //do all the output as necessary: _os << _e.variable;
}

最好同时实现输入运算符:

istream& operator>>(istream& _is, Employee& _e) {
  //get all the data: _is >> _e.variable;
}

您应该使这些友元函数对您的班级员工:

class Employee {
  public:
    //....
    friend ostream& operator<<(ostream& _os, const Employee& _e);
    friend istream& operator>>(istream& _is, Employee& _e);
    //....
}