Writing code to write object into a file, read them, and print on the screen
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
////////////////////////////////////////////////////////////
class employee{
private:
string name;
unsigned long ID;
public:
employee():name(""),ID(0){}
void putdata(){cout<<"Enter employee's name: ";cin>>name;cout<<"Enter employee's ID: ";cin>>ID;}
void getdata(){cout<<"Employee's name is: "<<name<<endl;cout<<"Employee's ID is: "<<ID<<endl;}
friend ostream& operator << (ostream&,employee&);
friend istream& operator >> (istream&,employee&);
};
ostream& operator << (ostream& f,employee& emp){ // запись объекта в файл
f<<emp.ID<<"-"<<emp.name<<"?";
return f;
}
istream& operator >> (istream& f,employee& empl){ // чтение объекта из файла
char dummy;
f>>empl.ID>>dummy;
f>>dummy;
empl.name="";
while(dummy!='?'){
empl.name+=dummy;
f>>dummy;
}
}
////////////////////////////////////////////////////////////
int main(){
char ch='y';
ofstream file1;
ifstream file2;
file1.open("TAB.txt");
employee one;
while(ch=='y'){ // цикл для записи
one.putdata();
file1<<one; // write data into file
cout<<"Go on?(y,n): ";cin>>ch;
}
file1.close();
file2.open("TAB.txt");
while(file2.good()){ // цикл для чтения из файла
file2>>one;
one.getdata();
}
file2.close();
system("pause");
return 0;
}
After entering objects, th program print them out and hanging. I guess there is a problem with while(file2.good()) but I'm not sure. Can anyone comment?