סדנא תרגיל 10

benny++C, סדנא ב++C, תרגילים, תרגילים בסדנא ב++C6 Comments

 

fstream c++ example

תרגיל בקבצים, קריאהמקובץ וכתיבה לקובץ ב ++C


/******************************
 
 targil: 10
 lecturer: david Cohen
 discription: opration on binary file
 
 *******************************/
#include <iostream>
#include <fstream>
using namespace std;

struct student//Structure that keeps data for each student.
{
	int id;//The number of student - this is the main key.
	char firstName[20];// first name.
	char lastName[20];// lest name.
	bool Courses[5];//A Boolean value. Containing true or false for 5 courses.
	student()//Default function. Initializes a student.
	{
		id=0;
		for (int i = 0; i < 5; i++)
			Courses[i]=0;
	}
};

//Function that checks whether the "Record" exists.
bool searchRecord(int _id, fstream& f)
{
	f.seekg((_id - 1)*sizeof(student), ios::beg);
	student s;
	f.read((char*)&s, sizeof(student));
	if (s.id == 0)
		return true;
	return false;
}

/*Adding a student. Function accepts a parameter pointer a binary file.
The function receives the data for students from standard input (keyboard).
If the resulting number of student still does not appear in the data file - 
the file will be added to student information.*/
void newStudent(fstream& f)
{
	student s;
	cout<<"Enter data for student: (id,first name,lest name,courses)"<<endl; cin>>s.id>>s.firstName>>s.lastName;
	for (int i = 0; i < 5; i++) cin>>s.Courses[i];
	if (searchRecord(s.id,f))
	{
		f.seekp((s.id-1)*sizeof(student));
	    f.write((char*)&s,sizeof(student));
	}
	else
	 cout << "student" << s.id<< " is exists\n";
}

/*Deleting a student. The function receives a pointer to a binary file as a
parameter and the second parameter, which is number of student. The function
deletes the file number is was received as a parameter student. (Note - You 
can format the primary key of the record only).*/
void deleteRecord(fstream &deleteFromFl)
{
	cout<<"Enter id to delete"<<endl; int tmpId; cin>>tmpId;
	if (!searchRecord(tmpId,deleteFromFl))
	{
		student blankStudent;
        deleteFromFl.seekp((tmpId-1)*sizeof(student));
		deleteFromFl.write((char*)&blankStudent,sizeof(student));
		cout<<"student "<< tmpId <<" deleted.\n";
   }
  else cout<<"student "<<tmpId<<" is empty.\n";
} 

/*Update listing. The function receives a pointer to a binary file as a parameter and
the second parameter, which is number of student. If the number of student listed in 
the data file, the function would absorb values for 5 courses standardinput and update 
the list of selected courses of student number is was received as a parameter.*/
void UpdateCourses(fstream &f,int _id)
{
	f.seekg((_id-1)*sizeof(student));
    student stu;
    f.read((char*)&stu,sizeof(student));
    if (!searchRecord(_id,f))
	{
		cout<<"enter true or false for courses:"<<endl;
		for (int i = 0; i < 5; i++) cin>>stu.Courses[i];
		f.write((char*)&stu,sizeof(student));
   }
  else cout<<"student "<<_id<<" is empty.\n";
}

/*Course listing examination. Function accepts a parameter pointer a binary file, the second
parameter, which is a number of students, and the third parameter which is course number (1 to 5).
If the number of student listed in the data file, and marking the course for student registration
this indicator that truth, this function returns true. Otherwise - function returns false.*/
bool listingInvestigation(fstream &f,int _id,int numCourse/*1-5*/)
{
	if (!searchRecord(_id,f))
	{
		cout<<"Student not found"<<endl;
		return 0;
	}
	f.seekg((_id-1)*sizeof(student));
    student stu;
    f.read((char*)&stu,sizeof(student));
    if (stu.id != 0 )
	{
		if (stu.Courses[numCourse])
			return true;
		return false;
   }
  else return false;
}

/*Print student information. Function accepts a parameter pointer a binary file, and the second parameter
that constitutes a number student. If the a number existing student data file, the function prints to 
standard output (screen) the student information: name, surname and for each course, if the student signed
up for will be printed: Y, otherwise, printed: N.*/
void printStudent(fstream &f,int _id)
{
	f.seekg((_id - 1)*sizeof(student), ios::beg);
	student stu;
	f.read((char *) &stu, sizeof(student));
	if (!searchRecord(_id,f))
	{
		cout<<stu.firstName<<" "<<stu.lastName<<" "<<endl;
		for (int i = 0; i < 5; i++)
		{
			if (stu.Courses[i])
				cout<<"Y"<<" "<<endl;
			else
				cout<<"N"<<" "<<endl;
		}
	}
	else
	 cout<<"student not found"<<endl;
}

/*Print a list of students in the course. Function accepts a parameter pointer a binary file, and the second
parameter that constitutes course number (1 to 5). The function prints to standard output (screen) the students'
information (name and surname), registered in the course, whose number is passed as a parameter.*/
void StudentsInTheCourse(fstream &f,int numCourse)
{
	for (int i = 1; i < 100; i++)
	{
		f.seekg((i - 1)*sizeof(student), ios::beg);
		student stu;
	    f.read((char *) &stu, sizeof(student));
	    if (stu.id)
			if (stu.Courses[numCourse])
				cout<<stu.firstName<<" "<<stu.lastName<<endl;
	}
}

void create()// Create students file
{	
	ofstream stu( "students.dat", ios::binary);
	if(!stu)
		cout<<"not open"<<endl;
	student s;  // Empty record
	for(int i=0;i<100;i++)
		stu.write((char*)&s,sizeof(student));
}

//The main program
int main()
{
	//system("color 2h");
	int choice,id,co;
	fstream fout("students.dat", ios::binary|ios::in | ios::out);
	create();
	cout << "enter your choise:"; cin >> choice;
	while (choice)
	{
		switch (choice)
		{
		case 1://Adding a student
			newStudent(fout);
			break;
		case 2://Deleting a student
			deleteRecord(fout);
			break;
		case 3://Update listing.
			cout<<"enter id:"<<endl; cin>>id;
			UpdateCourses(fout,id);
			break;
		case 4://Course listing examination.
			cout<<"enter id and number course: "<<endl; cin>>id>>co;
			if(listingInvestigation(fout,id,co))
				cout<<"true"<<endl;
			else
				cout<<"false"<<endl;
			break;
		case 5://Print student information
			cout<<"enter id:"<<endl; cin>>id;
			printStudent(fout,id);
			break;
		case 6://Print a list of students in the course.
			cout<<"enter number course:"<<endl; cin>>co;
			StudentsInTheCourse(fout,co);
			break;
		case 0:break;
		default:
			cout<<"ERROR"<<endl;
			break;
		}
		cout << "enter your choise:"; cin >> choice;
	}
	fout.close();
	return 0;
}

פיתרון נוסף

Student.h

#pragma once
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class Student
{
	int ID;
	char* familyName;
	char* privateName;
	bool course1;
	bool course2;
	bool course3;
	bool course4;
	bool course5;

public:
	Student(int id=0,char* f="",char*p ="");
	~Student();
	int getID() { return ID; }
	void setCourse(bool flag, int i);
	bool getCourse(int i);

	char* getPrivateName() { return privateName; }
	char* getFamilyName() { return familyName; }
};


student.cpp

#include "Student.h"

Student::Student(int id, char* f, char*p)
{
	ID = id;
	familyName = f;
	privateName = p;
	course1 = 0;
	course2 = 0;
	course3 = 0;
	course4 = 0;
	course5 = 0;
}


Student::~Student()
{
}

void Student::setCourse(bool flag, int i)
{
	switch (i)
	{
	case 1:
		course1 = flag;
	case 2:
		course2 = flag;
	case 3:
		course3 = flag;
	case 4:
		course4 = flag;
	case 5:
		course5 = flag;
	default:
		break;
	}
}

bool Student::getCourse(int i)
{
	switch (i)
	{
	case 1:
		return course1;
	case 2:
		return course2;
	case 3:
		return course3;
	case 4:
		return course4;
	case 5:
		return course5;
	default:
		break;
	}
}

main.cpp

#include "Student.h"

void initializeStudent(fstream& file)
{
	Student s; // empty object
	for (int i = 0; i < 100; i++)
	{
		file.write((char*)&s, sizeof(s));
	}
}

int enterChoice();
int getNum();
void newStudent(fstream & f);
void updateStudent(fstream & f, int num);
void deleteStudent(fstream & f, int num);
bool registrationForCourse(fstream &f, int num, int i);
void printStudent(fstream &f, int num);
void printStudentByCourse(fstream &f, int i);


int main()
{
	fstream file("file.txt");
	initializeStudent(file); // initialize file at 100 empty Student
	int choice = enterChoice();
	int tmp, i;

	while (choice != 0)
	{
		switch (choice)
		{
		case 1:
			newStudent(file); // add a new student to the file
			break;
		case 2:
			cout << "Enter num of student: "; cin >> tmp;
			deleteStudent(file, tmp); // remove student from file
			break;
		case 3:
			cout << "Enter num of student: "; cin >> tmp;
			updateStudent(file, tmp); // update a student courses
			break;
		case 4:
			cout << "Enter num of student: \n"; cin >> tmp;
			cout << "Enter num of course: \n"; cin >> i;
			cout << (registrationForCourse(file, tmp, i));
			break;
		case 5:
			cout << "Enter num of student: \n"; cin >> tmp;
			printStudent(file, tmp); // print student details
			break;
		case 6:
			cout << "Enter num of course: \n"; cin >> i;
			printStudentByCourse(file, i);
			break;
		default:
			break;
		}
	}
	return 0;
}

int enterChoice()
{
	//system("CLS");
	cout << "\nEnter your choice" << endl
		<< "1 - add a new student to the file" << endl
		<< "2 - remove student from file" << endl
		<< "3 - update a student courses" << endl
		<< "4 - to know if the student registare for a course" << endl
		<< "5 - print student details" << endl
		<< "6 - print student that in course i"<< endl
		<< "0 - end program\n? "; int menuChoice; cin >> menuChoice;
	return menuChoice;
}

int getNum()
{
	int studentNumber;
	
	cout << "Enter student number (1 - 100): "; cin >> studentNumber;
	while (studentNumber < 1 || studentNumber > 100)
	{
		cout << "ERROR\n";
		cout << "Enter student number (1 - 100): "; cin >> studentNumber;
	}
	return studentNumber;
}

void newStudent(fstream & f)
{
	Student s;
	int num = getNum();
	f.seekg((num - 1) * sizeof(s));
	f.read((char *)&s, sizeof(s));

	if (s.getID() == 0)
	{
		char familyName[20];
		char privateName[20];
		cout << "Enter familyName and privateName: "; cin >> familyName >> privateName;
		Student s1(num, familyName, privateName);
		f.seekp((num - 1) * sizeof(s1));
		f.write((char*)&s1, sizeof(s1));
	}
	else cout << "Account #" << num << " already contains information.\n";
}

void deleteStudent(fstream & f, int num)
{
	Student s;
	f.seekg((num - 1)*sizeof(s));
	f.read((char*)&s, sizeof(s));
	if (s.getID() != 0)
	{
		Student s1;	// Empty object
		f.seekp((num - 1)*sizeof(s1));
		f.write((char*)&s1, sizeof(s1));
		cout << "Account #" << num << " deleted.\n";
	}
	else
		cout << "ERROR! Account #" << num << " is empty.\n";
}

void updateStudent(fstream & f, int num)
{
	char flag;
	Student s;
	f.seekg((num - 1)*sizeof(s));
	f.read((char*)&s, sizeof(s));
	if (s.getID() != 0)
	{
		for (int i = 0; i < 5; i++)
		{
			cout << "Enter value of coures " << i+1 << " (0/1): "; cin >> flag;
			s.setCourse(flag, i+1);
		}
		f.seekp((num - 1)*sizeof(s));
		f.write((char*)&s, sizeof(s));
		cout << "Account #" << num << " updated.\n";
	}
	else
		cout << "ERROR! Account #" << num << " is empty.\n";
}

bool registrationForCourse(fstream & f, int num, int i)
{
	Student s;
	f.seekg((num - 1)*sizeof(s));
	f.read((char*)&s, sizeof(s));
	if (s.getID() != 0)
	{
		return s.getCourse(i);
	}
	else
		cout << "ERROR! Account #" << num << " is empty.\n";
	return 0;
}

void printStudent(fstream &f, int num)
{
	Student s;
	f.seekg((num - 1)*sizeof(s));
	f.read((char*)&s, sizeof(s));
	if (s.getID() != 0)
	{
		cout << "Name: " << s.getPrivateName() <<endl;
		cout << "Family name: " << s.getFamilyName() << endl;
		for (int i = 0; i < 5; i++)
		{
			cout<< "Course " << i;
			cout << (s.getCourse(i+1) ? ": Y\n" : ": N\n");
		}
	}
	else
		cout << "ERROR! Account #" << num << " is empty.\n";
}

void printStudentByCourse(fstream &f, int i)
{
	cout << "The Students are takes part in Course " << i << ":\n";
	Student s;
	for (int j = 0; i < 100; j++)
	{
		f.seekg((i)*sizeof(s));
		f.read((char*)&s, sizeof(s));
		if (s.getCourse(i))
		{
			cout << s.getPrivateName() << " " << s.getFamilyName() << endl;
		}
	}
} 

6 Comments on “סדנא תרגיל 10”

  1. בני יתותח העלת את כל הפטרונות שלי לקורס c++ .
    בני (שם בדוי )

    1. כל הפתרונות הם שלי, עד תרגיל 9 אבל גם אחרי תרגיל 9 זה לא שלך….

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *