gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:51:45 24 4
gpt4 key购买 nike

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

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;
}

您应该将这些友元函数添加到您的类 Employee 中:

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

关于c++ - 如何使用文件 I/O C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19505037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com