Similar to previous, make Student class with 4 data members (name, roll no, GPA, credit hours) and 2 constructors (one user input, one file input) and a destructor.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Student
{
public:
Student(string file);
Student();
~Student();
void Display();
private:
string name;
int rollNo;
double GPA;
int creditHours;
};
Student::Student()
{
cout << "User input constructor!" << endl;
cout << "Student name: ";
cin >> name;
cout << "Student roll no: ";
cin >> rollNo;
cout << "Student GPA: ";
cin >> GPA;
cout << "Student credit hours: ";
cin >> creditHours;
cout << "All data was entered new object Student successfully created!" << endl;
}
Student::Student(string file)
{
cout << "File input constructor!" << endl;
fstream in;
in.open(file);
if (!in)
{
cout << "There is no file with such name." << endl;
name = "";
rollNo = 0;
GPA = 0;
creditHours = 0;
return;
}
in >> name >> rollNo >> GPA >> creditHours;
cout << "New Student object was successfully created using data from file." << endl;
}
Student::~Student()
{
cout << "Student which name was " << name << " successfully destroyed!" << endl;
}
void Student::Display()
{
cout << "*****Student Information******" << endl;
cout << "Student name: " << name << endl;
cout << "Student roll no: " << rollNo << endl;
cout << "Student GPA: " << GPA << endl;
cout << "Student credit hours: " << creditHours << endl;
cout << "******************************" << endl;
}
int main()
{
Student User;
cout << endl;
User.Display();
cout << endl;
string fileName;
cout << "Enter file's name with Student data: ";
cin >> fileName;
Student studentFromFile(fileName);
studentFromFile.Display();
cout << endl;
return 0;
}
Comments
Leave a comment