Question

In: Computer Science

6.13 Lab: Patient Class - process an array of Patient objects This program will create an...

6.13 Lab: Patient Class - process an array of Patient objects

This program will create an array of 100 Patient objects and it will read data from an input file (patient.txt) into this array. Then it will display on the screen the following:

  • 1. The names of the underweight patients.
  • 2. The names of the overweight patients.
  • 3. The names of the obese patients.

Finally, it writes to another file (patientReport.txt) a table as shown below:

Weight Status Report
==================== === ====== ====== =============
Name                 Age Height Weight Status
==================== === ====== ====== =============
Jane North            25   66     120   Normal
Tim South             64   72     251   Obese
.
.
.
==================== === ====== ====== =============
Number of patients: 5

Assume that a name has at most 20 characters (for formatting). Write several small functions (stand-alone functions). Each function should solve a specific part of the problem.

On each line in the input file there are four items: age, height, weight, and name, as shown below:

25 66 120 Jane North    
64 72 251 Tim South

Prompt the user to enter the name of the input file. Generate the name of the output file by adding the word "Report" to the input file's name.

  • If the input file name is patient.txt, the output file name will be patientReport.txt
  • If the input file name is newPatients.txt, the output file name will be newPatientsReport.txt

Display the output file's name as shown below:

Report saved in:  patientReport.txt

If the user enters the incorrect name for the input file, display the following message and terminate the program:

Input file: patients.txt not found!

Here is a sample output:

Showing patients with the "Underweight" status:
Tim South
Linda East
Paul West
Victor Smith
Tom Baker

Showing patients with the "Overweight" status:
none
Showing patients with the "Obese" status:
none
Report saved in:  patient1Report.txt

Main.cpp:

#include "Patient.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;

const int MAX_SIZE = 100;

/* Write your code here:
declare the function you are going to call in this program
*/

int main()
{
Patient patArr[MAX_SIZE];
int size = 0;

string fileName;
cout << "Please enter the input file's name: ";
cin >> fileName;
cout << endl;
/* Write your code here:
function calls
*/
return 0;   
}

/* Write your code here:
function definitions
*/

/*
OUTPUT:

*/

Patient.h:

/*
Specification file for the Patient class
*/

#ifndef PATIENT_H
#define PATIENT_H
#include <string>

using std:: string;


class Patient
{
private:

string name;
double height;
int age;
int weight;

public:
// constructors
Patient();

Patient(string name, int age, double height, int weight);
// setters
void setName(string name);

void setHeight(double height);

void setAge(int age);

void setWeight(int weight);

//getters
string getName() const;

double getHeight() const;

int getAge() const;

int getWeight() const;

// other functions: declare display and weightStatus

void display() const;

string weightStatus() const;
};

#endif

Patient.cpp:

/*
Implementation file for the Patient class.
*/

#include "Patient.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

/*******
This is the default constructor; it sets everything to 0 or "".
*/
Patient::Patient()
{

name = "";
height = 0;
age = 0;
weight = 0;
}

/*******
This is an overloaded constructor.
It sets the variables according to the parameters.
*/
Patient::Patient(string name, int age, double height, int weight)
{

this->name = name;
this->height = height;
this->age = age;
this->weight = weight;

}

void Patient::setName(string name)
{
this->name = name;
}

void Patient::setHeight(double height)
{
this->height = height;
}

void Patient::setAge(int age)
{
this->age = age;
}

void Patient::setWeight(int weight)
{
this->weight = weight;
}

string Patient::getName() const
{
return this->name;
}

double Patient::getHeight() const
{
return this->height;
}

int Patient::getAge() const
{
return this->age;
}

int Patient::getWeight() const
{
return this->weight;
}

/*******
This function displays the member variables
in a neat format.
*/
void Patient::display() const
{
cout << fixed;
cout << " Name: " << getName() << endl;
cout << " Age: " << getAge() << endl;
cout << " Height: " << setprecision(0) << getHeight() << " inches" << endl;
cout << " Weight: " << getWeight() << " pounds" << endl;
cout << "Weight Status: " << weightStatus() << endl;
}

/*******
This function calculates the BMI using the following formula:
BMI = (weight in pounds * 703) / (height in inches)^2
Then, it returns a string reflecting the weight status according to the BMI:
<18.5 = underweight
18.5 - 24.9 = normal
25 - 29.9 = overweight
>=30 = obese
*/
string Patient::weightStatus() const
{
double bmi;
string stat = "";

if (height > 0)
{
bmi = (getWeight() * 703) / (getHeight() * getHeight());

if (bmi < 18.5)
{
stat = "Underweight";
}
else if (bmi >= 18.5 && bmi <= 24.9)
{
stat = "Normal";
}
else if (bmi >= 25 && bmi <= 29.9)
{
stat = "Overweight";
}
else
{
stat = "Obese";
}
}


return stat;
}

Solutions

Expert Solution

Answer-

Since I cannot attach any type of attachments here to the source code I have  written the code below:-

I have added the comments to understand the code better.

1. Code of the main file

#include "Patient.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

void readPatientData(Patient*, int*);
void displayAtRiskPatients(Patient*, string, int);
void writePatientReport(Patient*, int);

int main()
{
    Patient patArr[100];
    int noPatients = 0;

    readPatientData(patArr, &noPatients);
    cout << "The underweight patients: " << endl;
    displayAtRiskPatients(patArr, "Underweight", 17);
    cout << "The overweight patients: " << endl;
    displayAtRiskPatients(patArr, "Overweight", 17);
    cout << "The obese patients: " << endl;
    displayAtRiskPatients(patArr, "Obese", 17);
    writePatientReport(patArr, 17);
    return 0;
}

void readPatientData(Patient* patArr, int *SIZE)
{
    ifstream fin;
    string line, name;
    double height;
    int age, weight;

    fin.open("patient.txt");
    if (fin.fail())
    {
        cerr << "Input file could not be opened\n";
        exit(EXIT_FAILURE);
    }
    for (int i = 0; !fin.eof(); i++)
    {
        fin >> age;
        patArr[i].setAge(age);
        fin >> height;
        patArr[i].setHeight(height);
        fin >> weight;
        patArr[i].setWeight(weight);
        fin.ignore(); //Skips over space character
        getline(fin, name);
        patArr[i].setName(name);
        (*SIZE)++;
    }
    fin.close();
}

void writePatientReport(Patient* patArr, int size)
{
    ofstream fout;
    string name;

    fout.open("patientReport.txt");
    if (fout.fail())
    {
        cerr << "Output file cannot be opened at this time" << endl;
        exit(EXIT_FAILURE);
    }
    fout << "Weight Status Report\n"
    << "==================== === ====== ====== =============\n"
    << "Name " << setw(40) << "Age Height Weight Status" << "\n"
    << "==================== === ====== ====== =============" << endl;
    for (int i = 0; i < size; i++)
    {
        fout << setw(22) << left << patArr[i].getName()
        << setw(5) << patArr[i].getAge() << setw(7) << patArr[i].getHeight()
        << setw(5) << patArr[i].getWeight() << " " << patArr[i].weightStatus()
        << endl;
    }
    fout << "==================== === ====== ====== =============" << endl;
    fout << "Number of patients: " << size << endl;
    fout.close();
}

void displayAtRiskPatients(Patient* patArr, string w_status, int size)
{
    for (int i = 0; i < size; i++)
        if (patArr[i].weightStatus() == w_status)
            cout << patArr[i].getName() << endl;
    cout << endl;
}

The output will be shared below:-

The underweight patients:
Paul West
Laura King

The overweight patients:
Linda East

The obese patients:
Tim South
Tom Baker
William Peterson
Peter Pan
Andrew Davis

2. Code for Patient

#include "Patient.h"   // Needed for the Rectangle class
#include <iostream>      // Needed for cout
#include <string>
#include <cstdlib>       // Needed for the exit function
using namespace std;

void Patient::setName(string n)
{   name = n; }

void Patient::setAge(int a)
{
    if (a >= 1)
        age = a;
    else
    {
        cout << "Invalid age" << endl;
        exit(EXIT_FAILURE);
    }   
}

void Patient::setWeight(int w)
{
    if (w >= 0)
        weight = w;
    else
    {
        cout << "Invalid weight\n";
        exit(EXIT_FAILURE);
    }
}

void Patient::setHeight(double h)
{
    if (h >= 0)
        height = h;
    else
    {
        cout << "Invalid height\n";
        exit(EXIT_FAILURE);
    }
}

string Patient::weightStatus()
{
    string status;
    double BMI;

    BMI = (weight * 703.) / (height * height);
    if (BMI < 18.5)
        status = "Underweight";
    else if (BMI >= 18.5 && BMI <= 24.9)
        status = "Normal";
    else if (BMI >= 25. && BMI <= 29.9)
        status = "Overweight";
    else
        status = "Obese";
    return status;
}

void Patient::display()
{
    cout << "Name: " << name
    << "\nAge: " << age
    << "\nHeight: " << height << " inches"
    << "\nWeight: " << weight << " pounds"
    << "\nWeigh Status: " << weightStatus() << "\n" << endl;
}

3. code for patient.h


#ifndef PATIENT_H
#define PATIENT_H

#include <string> //ask about this
//using namespace std; why is it bad practice on .h files
class Patient
{
    private:
        std::string name;
        double height;
        int age, weight;
    public: //Public Interface 
        void setName(std::string);
        void setAge(int);
        void setWeight(int);
        void setHeight(double);
        void display();
        std::string weightStatus();

        std::string getName() const //inline functions
            { return name; }
        
        int getAge() const
            { return age; }

        int getWeight() const
            { return weight; }
        
        double getHeight() const
            { return height; }
        
        
};
#endif

Output:-


Related Solutions

In this class add Comparable interface. In the driver program create a few objects and In...
In this class add Comparable interface. In the driver program create a few objects and In the driver program create a few objects and compare them . then create a list of those objects and sort them .A Quadratic is bigger than another Quadratic if it opens faster package pack2; /** * This is a program for defining a quadratic equation * @author sonik */ public class Quadratic { public int coeffX2 = 0; public int coeffX = 0; public...
An exception with finally block lab. Create a new class named ReadArray Create simple array and...
An exception with finally block lab. Create a new class named ReadArray Create simple array and read an element using a try block Catch any exception Add a finally block and print a message that the operation if complete
please use C++ Create a class named Byte that encapsulates an array of 8 Bit objects....
please use C++ Create a class named Byte that encapsulates an array of 8 Bit objects. The Byte class will provide the following member functions: Byte - word: Bit[8] static Bit array defaults to all Bits false + BITS_PER_BYTE: Integer16 Size of a byte constant in Bits; 8 + Byte() default constructor + Byte(Byte) copy constructor + set(Integer): void sets Bit to true + clear(): void sets to 0 + load(Byte): void sets Byte to the passed Byte + read():...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount to represent a bank account according to the following requirements: A bank account has three attributes: accountnumber, balance and customer name. Add a constructor without parameters. In the initialization of the attributes, set the number and the balance to zero and the customer name to an empty string. Add a constructor with three parameters to initialize all the attributes by specific values. Add a...
Classes and Objects Write a program that will create two classes; Services and Supplies. Class Services...
Classes and Objects Write a program that will create two classes; Services and Supplies. Class Services should have two private attributes numberOfHours and ratePerHour of type float. Class Supplies should also have two private attributes numberOfItems and pricePerItem of type float. For each class, provide its getter and setter functions, and a constructor that will take the two of its private attributes. Create method calculateSales() for each class that will calculate the cost accrued. For example, the cost accrued for...
JAVA program Create a class called Array Outside of the class, import the Scanner library Outside...
JAVA program Create a class called Array Outside of the class, import the Scanner library Outside of main declare two static final variables and integer for number of days in the week and a double for the revenue per pizza (which is $8.50). Create a method called main Inside main: Declare an integer array that can hold the number of pizzas purchased each day for one week. Declare two additional variables one to hold the total sum of pizzas sold...
Create a class of DSA with two pointer objects of Employee and Customer. These objects will...
Create a class of DSA with two pointer objects of Employee and Customer. These objects will represent the head pointer of corresponding linkedlists. Add new data member functions searchCustomer & searchEmployee, to search for customers and employees separately in DSA.
Give an example of how to build an array of objects of a super class with...
Give an example of how to build an array of objects of a super class with its subclass objects. As well as, use an enhanced for-loop to traverse through the array while calling a static method(superclass x). Finally, create a static method for the class that has the parent class reference variable.
JAVASCRIPT Create an array of 5 objects named "movies" Each object in the movies array, should...
JAVASCRIPT Create an array of 5 objects named "movies" Each object in the movies array, should have the following properties: Movie Name Director Name Year Released WasSuccessful (this should be a boolean and at least 2 should be false) Genre Loop through all of the objects in Array If the movie is successful, display all the movie information on the page. These movies were a success: Title: Forrest Gump Year Realeased: 1994 Director: Robert Zemeckis Genre: Comedy
Instructions Create an application to accept data for an array of five CertOfDeposit objects, and then...
Instructions Create an application to accept data for an array of five CertOfDeposit objects, and then display the data. import java.time.*; public class CertOfDeposit { private String certNum; private String lastName; private double balance; private LocalDate issueDate; private LocalDate maturityDate; public CertOfDeposit(String num, String name, double bal, LocalDate issue) { } public void setCertNum(String n) { } public void setName(String name) { } public void setBalance(double bal) { } public void issueDate(LocalDate date) { } public String getCertNum() { }...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT