Write a program to perform file operations. Create a class student - add member variables - RollNo(Int), Name(string), Class(String), Division(char). Write a menu driven program to add student data in the file, display student data and search for a specific roll no in the file. New data should get added at the end of file when you run the program
Object Oriented Programming Assignment 4
Write a program to perform file operations. Create a class student - add member variables - RollNo(Int), Name(string), Class(String), Division(char). Write a menu driven program to add student data in the file, display student data and search for a specific roll no in the file. New data should get added at the end of file when you run the program
Code :
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Student
{
private:
int roll_no;
char name[20];
char Class[5];
char div;
public:
void add_data() // writing to file
{
fstream fs; // creating object of fstream
fs.open("myfile.txt",ios::out|ios::app); //opening file in append mode
if(!fs)
{
cout<<"file creation failed...";
exit(1);
}
else{
//cout<<" New file created..";
cout<<"\n Enter roll number :";
cin>>roll_no;
cout<<"\n Enter name :";
cin>>name;
cout<<"\n class :";
cin>>Class;
cout<<"\n Enter division :";
cin>>div;
// writing data to the file
fs << roll_no <<"\n ";
fs << name <<"\n ";
fs << Class <<"\n ";
fs << div <<"\n ";
cout<<"\n";
}
fs.close();
} // end of add data
void display_data() // reading from file
{
fstream fs;
fs.open("myfile.txt", ios::in);
if(!fs)
{
cout<<"No such file....";
}
else
{
while(!fs.eof()) // read till end of file
{
fs >> roll_no; // reading data from file//
fs >> name;
fs >> Class;
fs >> div;
if(!fs.eof())
{
cout<<"\n Roll:"<< roll_no <<"\n ";
cout<<"\n Name:"<< name<<"\n ";
cout<<"\n Class:"<< Class<<"\n ";
cout<<"\n Division:"<< div<<"\n ";
cout <<"\n";
}//end of if
}//end of while
fs.close();
}
}
void search_data()
{ fstream fs;
fs.open("myfile.txt",ios::in);
if(!fs)
{
cout<<"no such file....";
}
else
{ int rn;
cout<<"enter the roll no to be searched :";
cin>>rn;
while(!fs.eof()) // read till end of file
{
fs >> roll_no;
fs >> name;
fs >> Class;
fs >> div;
if(rn == roll_no)
{
cout<<"\n..... Record found......";
if(!fs.eof()) //checking whether reached eof
{
cout<<"\n roll no:"<<roll_no;
cout<<"\n name :"<<name;
cout<<"\n Class:"<<Class;
cout<<"\n Div:"<<div;
cout<<"\n";
}
}
}
fs.close();
}
}
};
int main()
{
Student s;
fstream fs;
int ch;
do{
cout<<"\n****Student information system****\n";
cout<<"\n................Menu..........................";
cout<<"\n 1. Add data ";
cout<<"\n 2. display data ";
cout<<"\n 3. Search ";
cout<<"\n 4. Exit ";
cout<<"\n Enter your choice :";
cin>>ch;
switch(ch)
{
case 1:
s.add_data();
break;
case 2:
s.display_data();
break;
case 3:
s.search_data();
break;
case 4:
exit(0);// exit of program
}
} while(ch != 4);// end of while
return 0;
}
Output :
Adding Data
Post a Comment