Skip to main content

Patient information store and retrieve

Short answer

To store and retrieve patient info, open patient.dat in binary append mode, write Patient objects using write(), then open for reading and display all records with read(). Fields use char arrays for binary I/O.

Write a program to store and retrieve the information of patient (Patient_ID, name, address, age and type) in hospital management system.

Assumption: patient data is stored as binary records in the file patient.dat; the program adds patients and then retrieves all of them.

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class Patient {
    int id;
    char name[30], address[30], type[20];   // type: e.g. OPD / Emergency
    int age;
public:
    void getData() {
        cout << "Patient ID: ";   cin >> id;
        cout << "Name: ";         cin.ignore(); cin.getline(name, 30);
        cout << "Address: ";      cin.getline(address, 30);
        cout << "Age: ";          cin >> age;
        cout << "Type: ";         cin.ignore(); cin.getline(type, 20);
    }
    void display() {
        cout << id << "\t" << name << "\t" << address << "\t"
             << age << "\t" << type << endl;
    }
};

int main() {
    Patient p;
    int n;
    cout << "How many patients? ";
    cin >> n;

    ofstream fout("patient.dat", ios::binary | ios::app);   // store
    for (int i = 0; i < n; i++) {
        p.getData();
        fout.write((char*)&p, sizeof(p));
    }
    fout.close();

    ifstream fin("patient.dat", ios::binary);                // retrieve
    cout << "\nID\tName\tAddress\tAge\tType\n";
    while (fin.read((char*)&p, sizeof(p)))
        p.display();
    fin.close();
    return 0;
}

write() and read() copy the whole object as bytes, so fixed-size character arrays are used instead of string.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →