Advertisements
Home > Cpp > C++ Program to implement File Handling by using ifstream & ofstream (Prg-1) – Q29

C++ Program to implement File Handling by using ifstream & ofstream (Prg-1) – Q29


Q29. Program to implement File Handling by using ifstream & ofstream:

Get the Rollno, Names and Marks Obtained of N students. The data should be stored in “RESULT” data file.
Use the same file to print the result along with aggregate percentage for all the students.

… from College notes (BCA/MCA assignments):

#include <iostream.h>
#include <fstream.h>
#include <conio.h>

class Cstud{
	private:
		char name[10];
		int roll, marks;
	public:
		void getdata();
		void putdata();
		int calc() const;
	};

void Cstud :: getdata(){
	cout<<"\n Enter Name: ";
	cin>>name;
	cout<<"\n Enter Roll No: ";
	cin>>roll;
	cout<<"\n Enter Marks: ";
	cin>>marks;
	}

int Cstud :: calc() const{
	return marks;
	}

void Cstud :: putdata(){
	cout<<"\n Name: "<<name;
	cout<<"\n Roll No: "<<roll;
	cout<<"\n Marks: "<<marks;
	}

void main(){
	int n, tot, avg;
	Cstud Ostu1, Ostu2;
	clrscr();
	cout<<"\n How many Students: ";
	cin>>n;
	ofstream fout;
	fout.open("result.txt", ios::out);
	for(int i=0; i<n; i++){
		cout<<"\n Student No: "<<i+1;
		Ostu1.getdata();
		fout.write((char *) &Ostu1, sizeof(Ostu1));
		}
	fout.close();

	ifstream fin;
	fin.open("result.txt", ios::in);
	tot = 0;
	clrscr();
	cout<<"\n Data read from File:- \n";
	for(i=0; i<n; i++){
		fin.read((char *) &Ostu2, sizeof(Ostu2));
		cout<<"\n\n Student No: "<<i+1;
		Ostu2.putdata();
		tot += Ostu2.calc();
		}
	avg = tot/n;
	cout<<"\n\n Total marks: "<<tot;
	cout<<"\n\n Average Marks: "<<avg;
	fin.close();
	getch();
	}

 

Output:

How many Students: 5

Student No: 1
Enter Name: manoj
Enter Roll No: 204
Enter Marks: 200

Student No: 2
Enter Name: Bhanu
Enter Roll No: 104
Enter Marks: 300

Student No: 3
Enter Name: Nitin
Enter Roll No: 214
Enter Marks: 350

Student No: 4
Enter Name: Prakash
Enter Roll No: 304
Enter Marks: 250

Student No: 5
Enter Name: Shilpi
Enter Roll No: 123
Enter Marks: 400

Student No: 1
Name: Manoj Roll No: 204 Marks: 200

Student No: 2
Name: Bhanu Roll No: 104 Marks: 300

Student No: 3
Name: Nitin Roll No: 214 Marks: 350

Student No: 4
Name: Prakash Roll No: 304 Marks: 250

Student No: 5
Name: Shilpi Roll No: 123 Marks: 400

Total marks: 1500
Average Marks: 300


Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: