// Program to overload stream operators for Student class (use files). // Assignment-34 // soovrld.cpp, Author - Krishna Kumar Khatri. // Uncomment ONLY the following line if you are using Turbo/Borland compiler. // #define TC #ifdef TC #include #include #else #include #include #include using namespace std; #endif #include // For getch. const int MAXLEN = 50; class Student { int rollno; char name[MAXLEN]; float marks; char filename[MAXLEN/2]; public: Student(char* fn = 0) { strcpy(filename, fn); } friend istream& operator>>(istream&, Student&); friend ostream& operator<<(ostream&, const Student&); }; istream& operator>>(istream& is, Student& st) { ofstream fn; cout << "Enter Roll no.: "; is >> st.rollno; cout << "Name: "; is >> st.name; cout << "Marks: "; is >> st.marks; fn.open(st.filename, ios::app); fn.write((char*)&st, sizeof(st)); fn.close(); return is; } ostream& operator<<(ostream& os, const Student& st) { ifstream fn(st.filename); fn.read((char*)&st, sizeof(st)); while (!fn.eof()) { os << endl << endl << "Roll no. - " << st.rollno << endl; os << "Name - " << st.name << endl; os << "Marks - " << st.marks; fn.read((char*)&st, sizeof(st)); } return os; } int main() { #ifdef TC clrscr(); #endif char filename[MAXLEN/2] = "Student.txt"; Student st(filename); int choice = 'y'; do { cout << "Enter data," << endl; cin >> st; cout << endl << "Continue insertion (y/n): "; choice = getche(); cout << endl << endl; } while (choice == 'y'); cout << "Saved data read as,"; cout << st; cout << endl << endl << "Program over. Press any key to exit..."; getch(); return 0; // Successful termination. }