Wednesday, January 31, 2018

Programming Challenge 15.8 - PreferredCustomer Class

Example Files: PreferredCustomer.7z

PersonData.h


#ifndef PERSON_DATA_H_
#define PERSON_DATA_H_

#include <string>
using std::string;

class PersonData
{
    private:
        string lastName;
        string firstName;
        string address;
        string city;
        string state;
        string zip;
        string phone;

    public:
        // Constructor
        PersonData()
        {
            lastName = " ";
            firstName = " ";
            address = " ";
            city = " ";
            state = " ";
            zip = " ";
            phone = " ";
        }

        // Parameterized constructor
        PersonData(string lName, string fName, string addr,
                      string cty, string st, string z, string telNum)
        {
            set(lName, fName, addr, cty, st, z, telNum);
        }

        // Mutator function
        // Sets the attribute data
        virtual void set(string lName, string fName, string addr, string cty,
                              string st, string z, string telNum)
        {
            lastName = lName;
            firstName = fName;
            address = addr;
            city = cty;
            state = st;
            zip = z;
            phone = telNum;
        }

        // Accessor functions
        string getLastName() const
        { return lastName; }

        string getFirstName() const
        { return firstName; }

        string getAddress() const
        { return address; }

        string getCity() const
        { return city; }

        string getState() const
        { return state; }

        string getZip() const
        { return zip; }

        string getPhone() const
        { return phone; }
};

#endif

CustomerData.h


#ifndef CUSTOMER_DATA_H_
#define CUSTOMER_DATA_H_

#include "PersonData.h"

// CustomerData class derived from PersonData class
class CustomerData : public PersonData
{
    private:
        int  customerNumber;            // A unique customer number
        bool mailingList;                // Holds the customer's wish to be on the mailing list

    public:
        // Constructor
        CustomerData()
        {
            customerNumber = 0;
            mailingList = false;
        }

        // Parameterized Constructor
        CustomerData(string lName, string fName, string addr, string cty, string st,
                         string zipNum, string telNum, int custID, bool onList) :
        PersonData(lName, fName, addr, cty, st, zipNum, telNum)
        {
            set(custID, onList);
        }

        // Mutator function
        // Sets the attribute data
        void CustomerData::set(int custID, bool onList)
        {
            customerNumber = custID;
            mailingList = onList;
        }

        // Accessor functions
        int getCustomerNumber() const
        { return customerNumber; }

        bool getMailingList() const
        { return mailingList; }
};

#endif

PreferredCustomer.h


#ifndef PREFERRED_CUSTOMER_H_
#define PREFERRED_CUSTOMER_H_

#include "CustomerData.h"

// PreferredCustomer class derived from the CustomerData class
class PreferredCustomer : public CustomerData
{
    private:
        double purchaseAmount;        // The total sum of purchases to date
        double discountLevel;        // The level of discount a customer has earned

    public:
        PreferredCustomer() : CustomerData()
        {
            purchaseAmount = 0.0;
            discountLevel = 0.0;
        }

        PreferredCustomer(string lName, string fName, string addr, string cty,
                                string st, string zipNum, string telNum, int custID,
                                bool onList, double pAmnt) :
        CustomerData(lName, fName, addr, cty, st, zipNum, telNum, custID, onList)
        {
            discountLevel = 0.0;

            setPurchaseAmount(pAmnt);
            setDiscountLevel();
        }

        // Mutator functions
        void setPurchaseAmount(double);        // Defined in PreferredCustomer.cpp
        void setDiscountLevel();               // Defined in PreferredCustomer.cpp

        // Accessor functions
        double getPurchaseAmount() const
        { return purchaseAmount; }

        double getDiscountLevel() const
        { return discountLevel * 100.0; }
};

#endif

PreferredCustomer.cpp


#include "PreferredCustomer.h"

#include <cstdlib>

#include <iostream>
using std::cout;

// Customer Discount Levels
enum DiscountLevels { LVL_ONE = 500, LVL_TWO = 1000, LVL_THREE = 1500, LVL_FOUR = 2000 };

/* **********************************************************
            PreferredCustomer::setPurchaseAmount() : double
    Sets the purchaseAmount attribute data. If the amount
    passed to this function is 0 or negative, the program
    will exit with an error message.
   ********************************************************** */

void PreferredCustomer::setPurchaseAmount(double pAmnt)
{
    if (pAmnt <= 0)
    {
        cout << "Input Error: " << pAmnt
              << " is an invalid purchase amount!\n"
              << "This program will now exit ...\n\n";
        exit(1);
    }
    else
    {
        purchaseAmount = pAmnt;
    }
}

/* **********************************************************
            PreferredCustomer::setDiscountLevel()
    Determines the amount of discount in % a customer is
    entitled to receive, based on the Preferred Customer
    Plan's purchase amounts to date.
   ********************************************************** */

void PreferredCustomer::setDiscountLevel()
{
    if (purchaseAmount < LVL_ONE)
    {
        discountLevel = 0.0;
    }
    else if (purchaseAmount < LVL_TWO)
    {
        discountLevel = 0.05;
    }
    else if (purchaseAmount < LVL_THREE)
    {
        discountLevel = 0.06;
    }
    else if (purchaseAmount < LVL_FOUR)
    {
        discountLevel = 0.07;
    }
    else
    {
        discountLevel = 0.1;
    }
}

PreferredCustomerDm.cpp


#include "PreferredCustomer.h"

#include <array>
using std::array;

#include <iomanip>
using std::setprecision;
using std::setw;

#include <iostream>
using std::cin;
using std::cout;
using std::fixed;

void printCustData(const array<PreferredCustomer, 3> &pData);

int main()
{
    // Create an array of 3 CustomerData objects
    array<PreferredCustomer, 3> pData
    {
        PreferredCustomer("Yamashita", "Tatsuro", "1 Chome-10 Haibaraakanedai",
                                "Uda-Shi", "Nara", "633-0256", "08984-1525", 15, false, 190.0),
        PreferredCustomer("Wang", "Kai", "2 Chome-7 Haibaraharumigaoka",
                                "Uda-Shi", "Nara", "633-0255", "08984-3256", 632, true, 587.70),
        PreferredCustomer("Hayakawa", "Keiko", "1 Chome-13-9 Haibaraakanedai",
                                "Uda-Shi", "Nara", "633-0257", "08984-4278", 947, true, 1489.90)
    };

    cout << "SunQ CITY SHOPPING MALL - CUSTOMER DATABASE\n\n";

    printCustData(pData);

    cout << "SunQ CITY SHOPPING MALL - Shopping Happiness!";
   
    cin.get();
    cin.ignore();
    return 0;
}

/* **********************************************************
            void printCustData() : const array &obj
    This function accepts an array of CustomerData objects. It
    outputs the customer information to screen.
   ********************************************************** */

void printCustData(const array<PreferredCustomer, 3> &pData)
{
    for (auto cData : pData)
    {
        cout << "Customer ID:     " << cData.getCustomerNumber() << "\n"
              << "On Mailing List: ";

        cData.getMailingList() == true ? cout << "Yes\n\n" : cout << "No\n\n";

        cout << "Last Name:       " << cData.getLastName() << "\n"
              << "First Name:      " << cData.getFirstName() << "\n"
              << "Address:         " << cData.getAddress() << "\n"
              << "City:            " << cData.getCity() << "\n"
              << "State:           " << cData.getState() << "\n"
              << "ZIP:             " << cData.getZip() << "\n"
              << "Phone Number:    " << cData.getPhone() << "\n\n";

        cout << fixed << setprecision(2);
        cout << "Purchase History:  " << setw(7) << cData.getPurchaseAmount() << " USD\n";
        cout << "Customer Discount: ";

        if (cData.getDiscountLevel() > 0)
        {
            cout << setw(7) << cData.getDiscountLevel() << " %\n";
        }
        else
        {
            cout << "Not a preferred customer\n";
        }
        cout << "\n---------------------------------------------" << "\n\n";
    }
}

Example Output:




Tuesday, January 30, 2018

Programming Challenge 15.7 - PersonData and CustomerData Classes

Example Files: PersonCustomerData.7z


PersonData.h


#ifndef PERSON_DATA_H_
#define PERSON_DATA_H_

#include <string>
using std::string;

class PersonData
{
    private:
        string lastName;
        string firstName;
        string address;
        string city;
        string state;
        string zip;
        string phone;

    public:
        // Constructor
        PersonData()
        {
            lastName = " ";
            firstName = " ";
            address = " ";
            city = " ";
            state = " ";
            zip = " ";
            phone = " ";
        }

        // Parameterized constructor
        PersonData(string lName, string fName, string addr,
                      string cty, string st, string z, string telNum)
        {
            set(lName, fName, addr, cty, st, z, telNum);
        }

        // Mutator function
        // Sets the attribute data
        virtual void set(string lName, string fName, string addr, string cty,
                              string st, string z, string telNum)
        {
            lastName = lName;
            firstName = fName;
            address = addr;
            city = cty;
            state = st;
            zip = z;
            phone = telNum;
        }

        // Accessor functions
        string getLastName() const
        { return lastName; }

        string getFirstName() const
        { return firstName; }

        string getAddress() const
        { return address; }

        string getCity() const
        { return city; }

        string getState() const
        { return state; }

        string getZip() const
        { return zip; }

        string getPhone() const
        { return phone; }
};

#endif

CustomerData.h


#ifndef CUSTOMER_DATA_H_
#define CUSTOMER_DATA_H_

#include "PersonData.h"

// CustomerData class derived from PersonData class
class CustomerData : public PersonData
{
    private:
        int  customerNumber;
        bool mailingList;

    public:
        // Constructor
        CustomerData()
        {
            customerNumber = 0;
            mailingList = false;
        }

        // Parameterized Constructor
        CustomerData(string lName, string fName, string addr, string cty, string st,
                         string zipNum, string telNum, int custID, bool onList) :
        PersonData(lName, fName, addr, cty, st, zipNum, telNum)
        {
            set(custID, onList);
        }

        // Mutator function
        // Sets the attribute data
        void CustomerData::set(int custID, bool onList)
        {
            customerNumber = custID;
            mailingList = onList;
        }

        // Accessor functions
        int getCustomerNumber() const
        { return customerNumber; }

        bool getMailingList() const
        { return mailingList; }
};

#endif

CustomerDataDm.cpp


#include "CustomerData.h"

#include <array>
using std::array;

#include <iostream>
using std::cin;
using std::cout;

void printCustData(const array<CustomerData, 3> &pData);

int main()
{
    // Create an array of 3 CustomerData objects
    array<CustomerData, 3> pData{ CustomerData("Yamashita", "Tatsuro", "1 Chome-10 Haibaraakanedai",
                                                              "Uda-Shi", "Nara", "633-0256", "08984-1525", 15, false),
                                             CustomerData("Wang", "Kai", "2 Chome-7 Haibaraharumigaoka",
                                                              "Uda-Shi", "Nara", "633-0255", "08984-3256", 632, true),
                                             CustomerData("Hayakawa", "Keiko", "1 Chome-13-9 Haibaraakanedai",
                                                              "Uda-Shi", "Nara", "633-0257", "08984-4278", 947, true) };

    cout << "SunQ CITY SHOPPING MALL - CUSTOMER DATABASE\n\n";

    printCustData(pData);

    cout << "SunQ CITY SHOPPING MALL - Shopping Happiness!";

    cin.get();
    cin.ignore();
    return 0;
}

/* **********************************************************
            void printCustData() : const array &obj
    This function accepts an array of CustomerData objects. It
    outputs the customer information to screen.
   ********************************************************** */

void printCustData(const array<CustomerData, 3> &pData)
{
    for (auto cData : pData)
    {
        cout << "Customer ID:     " << cData.getCustomerNumber() << "\n"
              << "On Mailing List: ";

        cData.getMailingList() == true ? cout << "Yes\n\n" : cout << "No\n\n";

        cout << "Last Name:       " << cData.getLastName() << "\n"
              << "First Name:      " << cData.getFirstName() << "\n"
              << "Address:         " << cData.getAddress() << "\n"
              << "City:            " << cData.getCity() << "\n"
              << "State:           " << cData.getState() << "\n"
              << "ZIP:             " << cData.getZip() << "\n"
              << "Phone Number:    " << cData.getPhone() << "\n";
        cout << "\n---------------------------------------------" << "\n\n";
    }
}

Example Output:



Sunday, January 28, 2018

Programming Challenge 15.6 - Essay Class

Example Files: EssayClass.7z

Notice: The GradedActivity.h and GradedActivity.cpp files are taken from the book and are provided as is.

GradedActivity.h


#ifndef GRADED_ACTIVITY_H_
#define GRADED_ACTIVITY_H_

class GradedActivity
{
    protected:
        double score;                // To hold the numeric score

    public:
        // Default constructor
        GradedActivity()
        { score = 0.0; }

        // Constructor
        GradedActivity(double s)
        { score = s; }

        // Mutator function
        void setScore(double s)
        { score = s; }

        // Accessor function
        double getScore() const
        { return score; }

        char getLetterGrade() const;
};

#endif

GradedActivity.cpp


#include "GradedActivity.h"

/* **********************************************************
            Member function GradedActivity::getLetterGrade()
   ********************************************************** */

char GradedActivity::getLetterGrade() const
{
    char letterGrade;        // To hold the letter grade

    if (score > 89)
    {
        letterGrade = 'A';
    }
    else if (score > 79)
    {
        letterGrade = 'B';
    }
    else if (score > 69)
    {
        letterGrade = 'C';
    }
    else if (score > 59)
    {
        letterGrade = 'D';
    }
    else
    {
        letterGrade = 'F';
    }

    return letterGrade;
}

Essay.h


#ifndef ESSAY_H_
#define ESSAY_H_

#include "GradedActivity.h"

// Max amount of achievable points
const int GRAMMAR = 30;
const int SPELLING = 20;
const int CORRECT_LENGTH = 20;
const int CONTENT = 30;

// Essay class derived from the GradedActivity class
class Essay : public GradedActivity
{
    private:
        double essayScore;            // The score a student has achieved
        int     grammar;                // Grammar score
        int    spelling;                // Spelling score
        int     length;                    // Correct length score
        int     content;                // Content score

    public:
        // Constructor
        Essay() : GradedActivity()
        {
            essayScore = 0.0;
            grammar = 0;
            spelling = 0;
            length = 0;
            content = 0;
        }

        // Parameterized constructor
        Essay(int gr, int sp, int len, int cont) : GradedActivity()
        {
            set(gr, sp, len, cont);
        }

        // Mutator functions
        void set(int, int, int, int);
        void addScore();

        // Accessor functions
        int getGrammarScore() const
        { return grammar; }

        int getSpellingscore() const
        { return spelling; }

        int getCorrectLengthScore() const
        { return length; }

        int getContentScore() const
        { return content; }
};

#endif

Essay.cpp


#include "Essay.h"

/* **********************************************************
            Essay::set() : int, int, int, int
    This function assigns the scores achieved by a student to
    the appropriate member variables.
   ********************************************************** */

void Essay::set(int gr, int sp, int len, int cont)
{
    grammar = gr;
    spelling = sp;
    length = len;
    content = cont;
}

/* **********************************************************
            Essay::addScore()
    This function calculates the total score achieved, then
    calls the inherited setScore() function to set the numeric
    score.
   ********************************************************** */

void Essay::addScore()
{
    essayScore = grammar + spelling + length + content;

    setScore(essayScore);
}

EssayDm.cpp


#include "Essay.h"

#include <iomanip>
using std::right;
using std::setw;

#include <iostream>
using std::cin;
using std::cout;

void getScores(int &, int &, int &, int &);
void displayGrade(const Essay &);

int main()
{
    int gr = 0;
    int sp = 0;
    int len = 0;
    int cont = 0;

    cout << "YAMAGATA 4th JUNIOR HIGH SCHOOL ESSAY GRADER\n\n";

    // Get the scores
    getScores(gr, sp, len, cont);

    // Create an Essay score object
    Essay essay(gr, sp, len, cont);
    essay.addScore();
   
    displayGrade(essay);

    cin.get();
    cin.ignore();
    return 0;
}

/* **********************************************************
            getScores() : int &, int &, int &, int &
    This function asks the teacher to input scores for the
    four categories that make up an essay's total score. The
    input is validated.
   ********************************************************** */

void getScores(int &gr, int &sp, int &len, int &cont)
{
    cout << "Enter the score for the following items:\n\n";
    cout << "Grammar (Max " << GRAMMAR << " points): ";
    cin >> gr;

    while (gr < 0 || gr > GRAMMAR)
    {
        cout << "Grammar: ";
        cin >> gr;
    }

    cout << "Spelling (Max " << SPELLING << " points): ";
    cin >> sp;

    while (sp < 0 || sp > SPELLING)
    {
        cout << "Spelling: ";
        cin >> sp;
    }

    cout << "Correct Length (Max " << SPELLING << " points): ";
    cin >> len;

    while (len < 0 || len > CORRECT_LENGTH)
    {
        cout << "Correct Length: ";
        cin >> len;
    }

    cout << "Content: (Max " << CONTENT << " points): ";
    cin >> cont;

    while (cont < 0 || cont > CONTENT)
    {
        cout << "Content: ";
        cin >> cont;
    }
}

/* **********************************************************
            displayGrade() : const obj &
    This function displays the scores achieved in each
    category, the total points and the letter grade.
   ********************************************************** */

void displayGrade(const Essay &essay)
{
    cout << "\n\nESSAY GRADER - SUMMARY\n\n";
    cout << "Essay Title: " << setw(10)
          << "ERASE BAD MEMORIES - KEEP GOOD ONES\n\n";

    cout << "GRAMMAR" << setw(14) << "SPELLING" << setw(12)
          << "LENGTH" << setw(14) << "CONTENT\n";
    cout << setw(7) << right << essay.getGrammarScore()
          << setw(14) << right << essay.getSpellingscore()
          << setw(12) << right << essay.getCorrectLengthScore()
          << setw(13) << right << essay.getContentScore() << "\n\n";

    cout << "Total  Score: " << essay.getScore() << "/100\n";
    cout << "Letter Grade: " << essay.getLetterGrade();
   
}

Example Output:



Thursday, January 25, 2018

Programming Challenge 15.5 - Time Clock

Example Files: TimeClock.7z

Notice: Time.h, MilTime.h, and MilTime.cpp have not changed, so they are contained in the Example Files 7-zip archive but not re-published here.

TimeClock.h


#ifndef TIME_CLOCK_H_
#define TIME_CLOCK_H_

#include "MilTime.h"

#include <sstream>
using std::stringstream;

// TimeClock class derived from the MilTime class
class TimeClock : public MilTime
{
    private:
        int startingTime;            // Starting time in military format
        int endingTime;            // Ending time in military format

    public:
        // Constructor
        TimeClock() : MilTime()
        {
            startingTime = 0;
            endingTime = 0;
        }

        // Parameterized constructor
        TimeClock(int sTHrs, int eTHrs) : MilTime()
        {
            setStartingTime(sTHrs);   
            setEndingTime(eTHrs);   
        }

        // Mutator functions
        void setStartingTime(const int);
        void setEndingTime(const int);
        int calcElapsedHours() const;
        int calcElapsedMinutes() const;

        // Accessor functions
        string TimeClock::getStartingTime()   
        {
            setTime(startingTime, 0);
            return getHour();
        }

        string getEndingTime()               
        {
            setTime(endingTime, 0);
            return getHour();
        }

        string getElapsedTime() const;
};

#endif

TimeClock.cpp


#include "TimeClock.h"

#include <iostream>
using std::cout;

#include <cstdlib>

/* **********************************************************
            TimeClock::setStartingTime() : const int
    If the argument passed to this function is valid, it is
    stored in the startingTime variable. Otherwise an error-
    message is output and the program exits.
   ********************************************************** */

void TimeClock::setStartingTime(const int sTHrs)
{
    if (isMilTime(sTHrs, 0) == true)
    {
        startingTime = sTHrs;
    }
    else
    {
        cout << "\nInput Error!\n"
            << sTHrs << " is no valid military time.\n"
            << "This program will now terminate ...\n";
        exit(0);
    }
}

/* **********************************************************
            TimeClock::setEndingTime() : const int
    If the argument passed to this function is valid, it is
    stored in the endingTime variable. Otherwise an error-
    message is output and the program exits.
   ********************************************************** */

void TimeClock::setEndingTime(const int eTHrs)
{
    if (isMilTime(eTHrs, 0) == true)
    {
        endingTime = eTHrs;
    }
    else
    {
        cout << "\nInput Error!\n"
            << eTHrs << " is no valid military time.\n"
            << "This program will now terminate ...\n";
        exit(0);
    }
}

/* **********************************************************
            TimeClock::calcElapsedHours()
    This function calculates and returns the number of hours
    that have passed.
   ********************************************************** */

int TimeClock::calcElapsedHours() const
{
    int elHrs = 0;

    endingTime > startingTime ? elHrs = (endingTime - startingTime) / 100 :
                                         elHrs = (startingTime - endingTime) / 100;
   
    return elHrs;
}

/* **********************************************************
            TimeClock::calcElapsedMinutes()
    This function calculates and returns the number of minutes
    that have passed.
   ********************************************************** */

int TimeClock::calcElapsedMinutes() const
{
    int elMins = 0;

    endingTime > startingTime ? elMins = (endingTime % 100) - (startingTime % 100) :   
                                         elMins = (startingTime % 100) - (endingTime % 100);

    if (elMins < 0)
    {
        elMins += 60;
    }

    return elMins;
}

/* **********************************************************
            TimeClock::getElapsedTime()
    This function formats and returns the elapsed time.
   ********************************************************** */

string TimeClock::getElapsedTime() const
{
    stringstream ss;
    ss.str("");
    ss.clear(stringstream::goodbit);
   
    int elapsedHrs = calcElapsedHours();
    int elapsedMins = calcElapsedMinutes();

    elapsedHrs == 1 ? ss << elapsedHrs   << " Hour " : ss << elapsedHrs << " Hours ";
    elapsedMins == 1 ? ss << elapsedMins << " Minute" : ss << elapsedMins << " Minutes";

    return ss.str();
}

TimeClockDm.cpp


#include "TimeClock.h"

#include <iostream>
using std::cin;
using std::cout;

void print(TimeClock &);

int main()
{
    int startingTime = 0;
    int endingTime = 0;

    cout << "TIME CLOCK - ELAPSED TIME CALCULATOR\n\n";
    cout << "This program lets you enter a starting and ending time\n"
          << "in military time format. It then calculates and displays\n"
          << "the elapsed time. Here is an example:\n";

    // Create a TimeClock object
    TimeClock clock(255, 2112);
    print(clock);

    // Create another TimeClock object
    TimeClock clockOne;

    // The user is asked to enter a starting and ending time
    // expressed in military hours
    cout << "Enter the starting time: ";
    cin >> startingTime;
    clockOne.setStartingTime(startingTime);
   
    cout << "Enter the ending time: ";
    cin >> endingTime;
    clockOne.setEndingTime(endingTime);
   
    print(clockOne);

    cout << "Thank you for trying the Elapsed Time Calculator! Have a nice day!";

    cin.get();
    cin.ignore();
    return 0;
}

/* **********************************************************
            print() : obj &
    This function accepts a TimeClock object. It outputs the
    starting, ending and elapsed time.
   ********************************************************** */

void print(TimeClock &tC)
{
    cout << "\n\nSTARTING TIME\n"
        << tC.getStartingTime() << "\n\n";
    cout << "ENDING TIME\n"
        << tC.getEndingTime() << "\n\n";
    cout << "TIME ELAPSED\n"
        << tC.getElapsedTime() << "\n\n\n";
}

Example Output:






Wednesday, January 24, 2018

Programming Challenge 15.4 - Time Format

Example Files: TimeFormat.7z

Notice: The code for the Time.h header file is taken vanilla from the book, nothing has been changed or added to it.

Time.h


#ifndef TIME_H_
#define TIME_H_

class Time
{
    protected:
        int hour;
        int min;
        int sec;

    public:
        // Default constructor
        Time()           
        {
            hour = 0;
            min = 0;
            sec = 0;
        }

        // Constructor
        Time(int h, int m, int s)           
        {
            hour = h;
            min = m;
            sec = s;
        }

        // Accessor functions
        int getHour() const
        { return hour; }

        int getMinute() const
        { return min; }

        int getSecond() const
        { return sec; }
};

#endif

MilTime.h


#ifndef MILTIME_H_
#define MILTIME_H_

#include "Time.h"

#include "string"
using std::string;

// MilTime class derived from the Time class
class MilTime : public Time
{
    protected:
        int milHours;            // Military hours (0 - 2359)
        int milSeconds;        // Military seconds (0 - 59)

    public:
        // Default Constructor
        MilTime() : Time()
        {
            milHours = 0;
            milSeconds = 0;
        }

        // Parameterized Constructor
        MilTime(int mHrs, int mSec) : Time(0, 0, 0)
        {
            setTime(mHrs, mSec);       
        }

        // Mutator functions
        bool isMilTime(const int, const int);
        void setTime(const int, const int);       
        void convertMilTime();

        // Accessor functions
        string getHour() const;
        string getStandHr() const;
};

#endif

MilTime.cpp


#include "MilTime.h"

#include <iostream>
using std::cin;
using std::cout;

#include <sstream>
using std::stringstream;

#include <cstdlib>

/* **********************************************************
            MilTime::setTime() : const int, const int
    If the values passed to this function are valid, the
    arguments are stored in the milHours and milSeconds
    variables. The time then gets converted to standard time.
    Otherwise an error message is output and the program will
    terminate.
    ********************************************************** */

void MilTime::setTime(const int mHrs, const int mSec)
{
    if (isMilTime(mHrs, mSec) == true)
    {
        milHours = mHrs;
        milSeconds = mSec;

        convertMilTime();
    }
    else
    {
        cout << "Input Error:\n";
      cout << mHrs << ':' << mSec << " is no military time!\n";
        cout << "This program will now exit.\n";
        exit(0);
    }
}

/* **********************************************************
            MilTime::isMilTime() : const int, const int
    This function evaluates the attributes to check whether it
    is a valid military time. The result of this evaluation is
    returned.
   ********************************************************** */

bool MilTime::isMilTime(const int mHrs, const int mSec)
{
    bool isValidMilTime = true;

    if (mHrs < 0 || mHrs > 2359 || mHrs % 100 >= 60)
    {
        isValidMilTime = false;
    }
    else if (mSec < 0 || mSec > 59)
    {
        isValidMilTime = false;
    }

    return isValidMilTime;
}

/* **********************************************************
            MilTime::convertMilTime()
    This function converts a military time to standard time,
    and stored in the hour, min and sec variables of the Time
    class.
   ********************************************************** */

void MilTime::convertMilTime()
{
    if (milHours > 1259)
    {
        hour = (milHours - 1200) / 100;
    }
    else if (milHours <= 59)
    {
        hour = 12;
    }
    else
    {
        hour = (milHours / 100);
    }

    min = milHours % 100;
    sec = milSeconds;
}

/* **********************************************************
            MilTime::getHour()
    This function formats and returns the hour in military
    format.
   ********************************************************** */

string MilTime::getHour() const
{
    stringstream ss;
    ss.str("");
    ss.clear(stringstream::goodbit);

    milHours < 10   ? ss << "000" << milHours << ':' :
    milHours < 100  ? ss << "00"  << milHours << ':' :
    milHours < 1000 ? ss << '0'   << milHours << ':' : ss << milHours << ':';

    milSeconds < 10 ? ss << '0'   << milSeconds << "Z Hours" : ss << milSeconds << "Z Hours";
   
    return ss.str();
}

/* **********************************************************
            MilTime::getStandHr()
    This function formats and returns the hour in standard
    format.
   ********************************************************** */

string MilTime::getStandHr() const
{
    stringstream ss;
    ss.str("");
    ss.clear(stringstream::goodbit);

    hour < 10 ? ss << '0' << hour << ':' : ss << hour << ':';
    min  < 10 ? ss << '0' << min  << ':' : ss << min << ':';
    sec  < 10 ? ss << '0' << sec             : ss << sec;

    milHours >= 1200 ? ss << " P.M." : ss << " A.M";

    return ss.str();
}

TimeFormat.cpp


#include "MilTime.h"

#include <iostream>
using std::cin;
using std::cout;

int main()
{
    int mHrs = 0;
    int mSecs = 0;

    cout << "MILITARY TIME CONVERTER\n\n";
    cout << "This program lets you convert Military to 'Standard' time.\n"
          << "Here is an example:\n\n";

    // Create a MilTime object and pass a military time to the constructor
    MilTime milTime(045, 7);
   
    cout << "MILITARY TIME\n";
    cout << milTime.getHour() << "\n\n";

    cout << "STANDARD TIME\n";
    cout << milTime.getStandHr() << "\n\n";

    // Create another MilTime object
    MilTime milTimeOne;

    // Ask the user to enter a military time
    cout << "Please enter a military time\n";
    cout << "Hour:   ";
    cin >> mHrs;
    cout << "Second: ";
    cin >> mSecs;
    cout << "\n";

    // Pass the values to the setTime() function of the MilTime class
    milTimeOne.setTime(mHrs, mSecs);

    cout << "MILITARY TIME\n";
    cout << milTimeOne.getHour() << "\n\n";

    cout << "STANDARD TIME\n";
    cout << milTimeOne.getStandHr() << "\n\n";

    cout << "Thank you for trying this program. Have a nice day!";

    cin.get();
    cin.ignore();
    return 0;
}

Example Output:





Saturday, January 20, 2018

Programming Challenge 15.3 - TeamLeader Class

Example Files: TeamLeaderClass.7z

Note: A change to the Employee and ProductionWorker class has been made. Both classes now contain a print function.

Employee.h


#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_

#include <string>
using std::string;

#include <iostream>
using std::ostream;

class Employee
{
    private:
        string empName;                // Employee name
        int     empID;                      // Employee ID-number
        string empHireDate;           // Employee hire date

    public:   
        // Default constructor
        Employee()
        {
            empName = " ";
            empID = 0;
            empHireDate = " ";
        }

        // Parameterized constructor
        Employee(string name, int number, string hireDate)
        {
            empName = name;
            empID = number;
            empHireDate = hireDate;
        }

        // Mutator functions
        void setEmpName(string name)
        { empName = name; }

        void setEmpID(int number)
        { empID = number; }

        void setEmpHireDate(string hireDate)
        { empHireDate = hireDate; }

        // Accessor functions
        string getEmpName() const
        { return empName; }

        int getEmpID() const
        { return empID; }

        string getEmpDateHired() const
        { return empHireDate; }

        // Friend function
        friend ostream &operator << (ostream &, const Employee &);

        // Virtual function defined in Employee.cpp
        virtual void print(ostream &strm) const;
};

#endif

Employee.cpp


#include "Employee.h"

#include <iomanip>
using std::setw;

#include <iostream>
using std::left;
using std::right;

/* **********************************************************
            Overloaded << operator
    Makes a call to the virtual print function, and sends the
    output to the stream.
   ********************************************************** */

ostream &operator << (ostream &strm, const Employee &obj)
{
    obj.print(strm);
    return strm;
}

/* **********************************************************
               Employee::print() : ostream &
    This function sends formatted employee data to the output
    stream.
   ********************************************************** */

void Employee::print(ostream &strm) const
{
    strm << left << setw(12) << "Employee Name: "
            << right << empName << "\n"
            << left << setw(12) << "Employee ID:   "
            << right << empID << "\n"
            << left << setw(15) << "Hire Date: "
            << right << empHireDate << "\n\n";
}

ProductionWorker.h


#ifndef PRODUCTION_WORKER_H_
#define PRODUCTION_WORKER_H_

#include "Employee.h"

#include <iostream>
using std::ostream;

// ProductionWorker class derived from the Employee class
class ProductionWorker : public Employee
{
    protected:
        int    shiftNumber;                // The shift number (1 = day, 2 = night)
        double hourlyPayRate;            // The hourly pay rate

    public:
        // Default constructor
        ProductionWorker() : Employee()
        {
            shiftNumber = 0;
            hourlyPayRate = 0.0;
        }

        // Parameterized Constructor
        ProductionWorker(string name, int number, string hireDate, int shift, double payRate) :
                  Employee(name, number, hireDate)
        {
            shiftNumber = shift;
            hourlyPayRate = payRate;
        }

        // Mutator functions
        void setShift(int shift)
        { shiftNumber = shift; }

        void setHourlyPayrate(double payRate)
        { hourlyPayRate = payRate; }

        // Accessor functions
        int getShift() const
        { return shiftNumber; }

        double getHourlyPayRate() const
        { return hourlyPayRate; }

        void print(ostream &) const;
};

#endif

ProductionWorker.cpp


#include "ProductionWorker.h"

#include <iomanip>
using std::setprecision;
using std::setw;

#include <iostream>
using std::left;
using std::right;
using std::fixed;

/* **********************************************************
            ProductionWorker::print() : ostream & (overridden)
   ********************************************************** */

void ProductionWorker::print(ostream &strm) const
{
    Employee::print(strm);

    strm << "Shift #" << shiftNumber << ": ";

    shiftNumber == 1 ? strm << setw(16) << right << " Day-Shift\n" :
                                    strm << setw(16) << right << " Night-Shift\n";

    strm << fixed << setprecision(2)
            << left << setw(14) << "Pay Rate: "
            << right << "$ " << hourlyPayRate << "\n";
}

TeamLeader.h


#ifndef TEAM_LEADER_H_
#define TEAM_LEADER_H_

#include "ProductionWorker.h"

// TeamLeader class derived from the ProductionWorker class
class TeamLeader : public ProductionWorker
{
    private:
        double monthlyBonus;                    // Monthly salary bonus
        int    attTrainingHours;                    // Attented training hours

    public:
        const int REQ_TRAINING_HOURS = 75;        // Required hours of traning p.A.

        // Constructor
        TeamLeader() : ProductionWorker()
        {
            monthlyBonus = 0.0;
            attTrainingHours = 0;
        }

        // Parameterized constructor
        TeamLeader(string name, int number, string hireDate, int shift, double payRate,
                      double bonus) :
        ProductionWorker(name, number, hireDate, shift, payRate)
        {
            monthlyBonus = bonus;
            attTrainingHours = 0;
        }

        // Mutator functions
        void setMonthlyBonus(double bonus)
        { monthlyBonus = bonus; }

        void setAttTrainingHours(int attHours)
        { attTrainingHours = attHours; }

        // Accessor functions
        double getMonthlyBonus() const
        { return monthlyBonus; }

        int getAttendedTrainingHours() const
        { return attTrainingHours; }

        int getRemainingTrainingHours() const;   

        // Overridden print function
        void print(ostream &) const;
};

#endif

TeamLeader.cpp


#include "TeamLeader.h"

#include <iomanip>
using std::setw;

#include <iostream>
using std::left;
using std::right;

/* **********************************************************
            TeamLeader::getRemainingTrainingHours()
    This function determines, how many hours of traning are
    left to take for a team leader, in order to fulfill the
    mandatory training requirements.
   ********************************************************** */

int TeamLeader::getRemainingTrainingHours() const
{
    int remainingHours = 0;

    return remainingHours = (REQ_TRAINING_HOURS - attTrainingHours);
}

/* **********************************************************
            TeamLeader::print() : ostream & (overridden)
   ********************************************************** */

void TeamLeader::print(ostream &strm) const
{
    ProductionWorker::print(strm);

    strm << left << setw(14) << "Bonus: "
            << right << "$ " << monthlyBonus << "\n\n"
            << "ANNUAL TRAINING REQUIREMENTS\n\n"
            << "Required:  " << REQ_TRAINING_HOURS << " hrs.\n"
            << "Attended:  " << attTrainingHours << " hrs.\n"
            << "Remaining: " << getRemainingTrainingHours() << " hrs.\n";   
}

TeamLeaderClass.cpp


 #include "TeamLeader.h"

#include <array>
using std::array;

#include <iostream>
using std::cin;
using std::cout;

int main()
{
    // Create a TeamLeader object
    TeamLeader leader("Takahashi Hideki", 92358, "05/07/2014", 1, 39.70, 19.50);
   
    // Create an array of three ProductionWorker objects. Each employee is
    // part of this team leader's team.
    array <ProductionWorker, 3> worker
    {
        ProductionWorker("Hartwood Michael", 23727, "05/07/2016", 1, 14.70),   
        ProductionWorker("Talmar Arman", 54838, "03/03/2005", 1, 29.50),
        ProductionWorker("Clayborn Dolores", 54257, "05/04/2015", 1, 17.50)
    };

    cout << "TAKEUCHI MANUFACTURING CO. - TRACK LOADER ASSEMBLY TEAM\n\n";
    cout << "TEAM LEADER\n\n";
    leader.setAttTrainingHours(35);
    cout << leader;

    cout << "\n\nPRODUCTION TEAM\n\n";
    for (auto workerTeam : worker)
    {
        cout << workerTeam << "\n";
    }
   
    cout << "TAKEUCHI MANUFACTURING CO.\n"
          << "Unrivaled quality, products with a difference,\n"
          << "and fast development responding to the users' needs.";

    cin.get();
    cin.ignore();
    return 0;
}

Example Output:




Friday, January 19, 2018

Programming Challenge 15.2 - ShiftSupervisor Class

Example Files: ShiftSupervisorClass.7z

ShiftSupervisor.h


#include "Employee.h"

// ShiftSupervisor class derived from Employee
class ShiftSupervisor : public Employee
{
    private:
        double annualSalary;                // Annual salary
        double annualBonus;                // Annual bonus

    public:
        // Constructor
        ShiftSupervisor() : Employee()
        {
            annualSalary = 0.0;
            annualBonus = 0.0;
        }

        // Parameterized Constructor
        ShiftSupervisor(string name, int number, string hireDate,
                             double salary) :
                Employee(name, number, hireDate)
        {
            annualSalary = salary;
        }

        // Mutator functions
        void setAnnualSalary(double salary)
        { annualSalary = salary; }

        void setAnnualBonus(double bonus)
        { annualBonus = bonus; }

        void calcAnnualBonus()
        { annualBonus *= annualSalary; }

        // Accessor functions
        double getAnnualSalary() const
        { return annualSalary; }

        double getAnnualBonus() const
        { return annualBonus; }

        double getTotalSalary() const
        { return annualSalary + annualBonus; }
};

#endif

ShiftSupervisorClass.cpp


#include "ShiftSupervisor.h"

#include <iomanip>
using std::setprecision;
using std::setw;

#include <iostream>
using std::cin;
using std::cout;
using std::left;
using std::right;
using std::fixed;

const double BONUS = 0.10;
const int    PRODUCTION_GOAL = 128948;

void getProductionData(ShiftSupervisor &);
bool isGoalMet(const int &);
void outputData(const ShiftSupervisor &);

int main()
{
    // Create a ShiftSupervisor object
    ShiftSupervisor supervisor("Corum J. Irsei", 29835, "05/07/2016", 25760.0);

    cout << "TAKEUCHI MANUFACTURING CO. - FINANCE DEPARTMENT\n\n";
    cout << "Enter number of units produced at this supervisor's line\n"
          << "to determine whether annual salary bonus applies.\n\n";
    getProductionData(supervisor);

    cout << "TAKEUCHI MANUFACTURING CO. - PAYROLL SYSTEM\n\n";
    outputData(supervisor);

   cout << "You are now leaving the Database System ...\n\n";
   cout << "TAKEUCHI MANUFACTURING CO.\n"
        << "Unrivaled quality, products with a difference,\n"
        << "and fast development responding to the users' needs.";

    cin.get();
    cin.ignore();
    return 0;
}

/* **********************************************************
           getProductionData() : const obj &
    This function asks the user to input the number of units
     produced at a supervisor's line. If the production goal
     has been met, the bonus is set and the amount of bonus
     calculated. Otherwise the bonus is set to 0.0.
   ********************************************************** */

void getProductionData(ShiftSupervisor &supervisor)
{
    int unitsTotal = 0;
   
    cout << "Supervisor Name: " << supervisor.getEmpName() << "\n"
          << "Supervisor ID-#: " << supervisor.getEmpID() << "\n";
    cout << "Production Goal: " << PRODUCTION_GOAL << " Units\n\n";

    cout << "Number of units produced: ";
    cin >> unitsTotal;

    while (unitsTotal < 85000 || unitsTotal >= 135000)
    {
        cout << "Number of units produced (Min: 85000, Max: 135000): ";
        cin >> unitsTotal;
    }
    cout << "\n";

    if (isGoalMet(unitsTotal) == true)
    {
        supervisor.setAnnualBonus(BONUS);
        supervisor.calcAnnualBonus();
    }
    else
    {
        supervisor.setAnnualBonus(0.0);
    }
}

/* **********************************************************
           isGoalMet() : const int &
    This function determines whether the production goal has
    been met.
   ********************************************************** */

bool isGoalMet(const int &units)
{
    bool goalMet = false;

    if (units >= PRODUCTION_GOAL)
    {
        cout << "Production Goal Met!\n";
        goalMet = true;
    }

    return goalMet;
}

/* **********************************************************
            outputData() : const obj &
    This function outputs a supervisor's personal data, his
     or her annual salary, annual bonus and total salary.
   ********************************************************** */

void outputData(const ShiftSupervisor &supervisor)
{
    cout << left << setw(12) << "Supervisor: "
          << right << supervisor.getEmpName() << "\n"
          << left << setw(12) << "ID-Number: "
          << right << supervisor.getEmpID() << "\n"
          << left << setw(11) << "Date Hired: "
          << right << supervisor.getEmpDateHired() << "\n\n";

    cout << fixed << setprecision(2);

    cout << left << setw(17) << "Annual Salary: $ "
          << right << supervisor.getAnnualSalary() << "\n";
    cout << left << setw(17) << "Annual Bonus:  $ "
          << right << setw(8) << supervisor.getAnnualBonus() << "\n";
    cout << left << setw(17) << "Total Salary:  $ "
          << right << supervisor.getTotalSalary() << "\n\n";
}


Example Output: