Reputation: 374
First I'm trying to create a file and write to it, it is not letting me use the "<<" to write to the file, and the second part I'm trying to read the data from the file but I'm not certain that is the right way since I want to save the data into the objects so I can use the objects later in my program. Any help or suggestions are greatly appreciated. Thanks in advance
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();
}
Upvotes: 1
Views: 149
Reputation: 4939
The error you are receiving is because you need to define an output operator for the employee class.
ostream& operator<<(ostream& _os, const Employee& _e) {
//do all the output as necessary: _os << _e.variable;
}
It is a good idea to also implement the input operator:
istream& operator>>(istream& _is, Employee& _e) {
//get all the data: _is >> _e.variable;
}
You should make these friend functions to your class Employee:
class Employee {
public:
//....
friend ostream& operator<<(ostream& _os, const Employee& _e);
friend istream& operator>>(istream& _is, Employee& _e);
//....
}
Upvotes: 3