Record Handling
Example:1
C++ Program to maintain student details like roll, name, and age. (Menu Driven program)
Sol:
In this progranm we maintain student details
Roll no
Name
Age
This program is menu driven and deals with only two operations,
1. Adding the record
2. Displaying all the records
Functions used:
add()
To add record in the file
disp()
To dislplay a single record
heading();
To display heading while displaying records
get_input();
To take input for details
disp_all();
To display all the records
menu();
To display menu
#include<iostream> #include<fstream> #include<stdio.h> #include<conio.h> #include<string.h> using namespace std; class student { private: int roll; char name[10]; float age; public: void add(); void disp(); void heading(); void get_input(); void disp_all(); void menu(); }; void student::heading() { cout<<"Student Details"<<endl; cout<<"----------------"<<endl; cout<<"Roll name age "<<endl; } void student::get_input() { cout<<"Enter the Roll Number "; cin>>roll; cout<<"Enter the First name "; fflush(stdin); cin>>name; strupr(name); cout<<"Enter the age "; cin>>age; } void student::disp() { cout<<roll<<" "<<name<<" "<<age<<endl; } void student::add() { student s1; fstream file; file.open("stud1.dat",ios::in); if (file.fail()) { cout<<"Unable to open the file, file does not exist\n"; file.open("stud1.dat",ios::out); } else { cout<<"File is present , so should be opened in append mode \n"; file.close(); file.open("stud1.dat",ios::app); } s1.get_input(); file.write((char*)&s1,sizeof(s1)); file.close(); } void student::disp_all() { student s1; fstream file; file.open("stud1.dat",ios::in); if (file.fail()) { cout<<"Unable to open the file "; getch(); return; } file.read((char*)&s1,sizeof(s1)); //here// s1.heading(); while(!file.eof()) { s1.disp(); file.read((char*)&s1,sizeof(s1)); } file.close(); } void student::menu() { cout<<"Main Menu "<<endl; cout<<"1. Addition of record "<<endl; cout<<"2. Display of all the record "<<endl; cout<<"3. Exit "<<endl; cout<<"Enter your choice "; } int main() { student s1; int op=0; while(op!=3) { s1.menu(); cin>>op; switch(op) { case 1: s1.add(); break; case 2: s1.disp_all(); break; case 3: cout<<"End of the program "<<endl; break; default: cout<<"invalid option entered \n"; break; } getch(); } return(0); }