Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
2.8 kB
2
Indexable
#include <iostream>
#include <fstream>
using namespace std;
class Student
{
private:
    string name;
    int roll_number;
    int marks;

public:
    Student()
    {
        name = " ";
        roll_number = 0;
        marks = 0;
    }
    Student(string name, int roll_number, int marks)
    {
        this->name = name;
        this->roll_number = roll_number;
        this->marks = marks;
    }
    void write_to_file();
    void read_from_file();
    void append_to_file();
};

void Student::write_to_file()
{
    ofstream file;
    file.open("Records.txt");
    if (!file)
    {
        cout << "File creation failed!!" << endl;
    }
    else
    {

        cout << "Enter name: ";
        cin >> name;
        cout << "Roll number: ";
        cin >> roll_number;
        cout << "Marks: ";
        cin >> marks;
        file << name << " " << roll_number << " " << marks << endl;
        file.close();
    }
    return;
}
void Student::append_to_file()
{
    fstream file;
    file.open("Records.txt", ios::app);
    if (!file)
    {
        cout << "File creation failed!!" << endl;
    }
    else
    {

        cout << "Enter name: ";
        cin >> name;
        cout << "Roll number: ";
        cin >> roll_number;
        cout << "Marks: ";
        cin >> marks;
        file << name << " " << roll_number << " " << marks << endl;
        file.close();
    }
    return;
}
void Student::read_from_file()
{
    ifstream file;
    string l;
    file.open("Records.txt", ios::in);
    if (!file)
    {
        cout << "File Not present" << endl;
        return;
    }
    else
    {
        while (!file.eof())
        {
            getline(file, l);
            cout << l << endl;
        }
        file.close();
    }
    return;
}

int main()
{
    int ch;
    bool loop = true;
    Student obj;
    while (loop)
    {
        cout << "********************************\n"
             << endl;
        cout << "STUDENT MANAGEMENT SYSTEM" << endl;
        cout << "********************************\n"
             << endl;
        cout << "1. Write data(To new file)" << endl;
        cout << "2. Append data(To same file)" << endl;
        cout << "3. Read data" << endl;
        cout << "4. Exit" << endl;
        cout << "Enter operation : ";
        cin >> ch;

        switch (ch)
        {
        case 1:
            obj.write_to_file();
            break;
        case 2:
            obj.append_to_file();
            break;
        case 3:
            obj.read_from_file();
            break;
        case 4:
            loop = false;
            break;
        default:
            cout << "Enter valid operation!!!!!" << endl;
            break;
        }
    }
    return 0;
}