首先,我正在尝试创建一个文件并写入它,它不会让我使用“<<”写入文件,第二部分我正在尝试从文件中读取数据,但我不确定这是正确的方法因为我想将数据保存到对象中所以我可以在以后使用这些对象我的节目。非常感谢任何帮助或建议。提前致谢
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();
}
答案 0 :(得分:3)
您收到的错误是因为您需要为员工类定义输出运算符。
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);
//....
}