Thursday, February 22, 2018

Programming Challenge 16.7 - TestScores Class

Example Files: TestScoresClass.7z

TestScores.h


#ifndef TEST_SCORES_H_
#define TEST_SCORES_H_

class TestScores
{
    private:
        int *scorePtr;
        int arraySize;
        int averageScore;

    public:
        // Exception class
        class OutOfRange
        {
            private:
                int errScore;

            public:
                OutOfRange(int subscript)
                {
                    errScore = subscript;
                }

                int getErrSubscript() const
                { return errScore; }
        };

        TestScores(int);
        TestScores(const TestScores &);
        ~TestScores();
   
        // Accessor function
        void calcAverage();

        // Mutator function
        int getAverageScore() const
        { return averageScore; }

        // Overloaded operator functions
        const TestScores operator = (const TestScores &);
        int &operator [](const int &sub);
};

#endif

TestScores.cpp


#include "TestScores.h"

/* **********************************************************
            TestScores::TestScores() - Constructor
    Sets the size of the array and allocates memory for it.
   ********************************************************** */

TestScores::TestScores(int size)
{
    averageScore = 0;

    arraySize = size;
    scorePtr = new int[size];

    for (int count = 0; count < arraySize; count++)
    {
        *(scorePtr + count) = 0;
    }
}

/* **********************************************************
            TestScores::TestScores() - Copy Constructor  
   ********************************************************** */

TestScores::TestScores(const TestScores &obj)
{
    arraySize = obj.arraySize;
    scorePtr = new int[arraySize];

    for (int count = 0; count < arraySize; count++)
    {
        *(scorePtr + count) = *(obj.scorePtr + count);
    }
}

/* **********************************************************
            TestScores::~TestScores() - Destructor
   ********************************************************** */

TestScores::~TestScores()
{
    if (arraySize > 0)
    {
        delete [] scorePtr;
    }
}

/* **********************************************************
            TestScores::operator =() : const obj &
    This function performs a self-assignment check.
   ********************************************************** */

const TestScores TestScores::operator = (const TestScores &right)
{
    if (this != &right)
    {
        delete [] scorePtr;

        arraySize = right.arraySize;
        scorePtr = new int[arraySize];

        for (int count = 0; count < arraySize; count++)
        {
            *(scorePtr + count) = *(right.scorePtr + count);
        }
    }

    return *this;
}

/* **********************************************************
            TestScores::calcAverage()
    This function calculates the average of all test scores.
    If a score is lower 0 or greater 100, the OutOfRange
    exception is thrown. Otherwise the score is accumulated,
    and the average score is calculated, before the function
    exits.
   ********************************************************** */

void TestScores::calcAverage()
{
    int sumTotal = 0;

    for (int count = 0; count < arraySize; count++)
    {
        if (*(scorePtr + count) < 0 || *(scorePtr + count) > 100)
        {
            throw OutOfRange(count);
        }
        else
        {
            sumTotal += *(scorePtr + count);
        }
    }

    averageScore = (sumTotal / arraySize);
}

/* **********************************************************
            TestScores::operator []() : const int &
    Returns a reference to the element in the array indexed by
    the subscript.
   ********************************************************** */

int &TestScores::operator [](const int &sub)
{
    return scorePtr[sub];
}

TestScoresDm.cpp


#include "TestScores.h"

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

#include <string>
using std::string;

/* **********************************************************
                            Function Definition 
   ********************************************************** */

void evalScores(TestScores &, const int);

int main()
{
    const int SIZE = 5;
    const int NUM_STUDENTS = 3;
    int         score = 0;
   
    const string studentNames[NUM_STUDENTS]{ "M. Hiroshi", "A. Ogawa", "M. Takahata" };

    TestScores scoreArr(SIZE);

    cout << "YAMAGATA 4th JUNIOR HIGH SCHOOL - AVERAGE TEST SCORE CALCULATOR\n\n";

    for (int index = 0; index < NUM_STUDENTS; index++)
    {
        cout << "Student Name: " << studentNames[index] << "\n\n";
        for (int count = 0; count < SIZE; count++)
        {
            cout << "Test-Score #" << (count + 1) << ": ";
            cin >> scoreArr[count];
        }

        evalScores(scoreArr, SIZE);

        cout << "\nThe average score of this student is: "
              << scoreArr.getAverageScore() << "\n";
    }
    cout << "\n";

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

/* **********************************************************
            evalScores() : obj &, const int
    When the try/catch block in this function executes, the
    object's calcAverage() function is called. If all scores
    are found to be valid, the function exits. Otherwise the
    user is repeatedly asked to input a valid value until one
    is entered. This new value is assigned to the appropriate
    array subscript position.
   ********************************************************** */

void evalScores(TestScores &scoreArr, const int size)
{
    bool tryAgain = true;

    while (tryAgain)
    {
        try
        {
            scoreArr.calcAverage();
            tryAgain = false;
        }
        catch (TestScores::OutOfRange score)
        {
            cout << "\nInvalid Score: " << scoreArr[score.getErrSubscript()] << "\n";
            cout << "Enter a valid score: ";
            cin >> scoreArr[score.getErrSubscript()];
        }
    }
}

Example Output:



Wednesday, February 21, 2018

Programming Challenge 16.6 - IntArray Class Exception

Example Files: IntArrayClassException.7z

Notice: Most of the code is taken from chapter 14, pp. 858 - 863 in the 9th Edition, or pp. 853 through 857 in the 8th Edition of the book. Notice also that there are two versions of the driver program for this programming challenge. One is listed in this solution, the other is contained in the Example Files archive and is called called "IntArrayExceptionSimple.cpp." The last screenshot demonstrates the output of this second driver program.

IntArray.h


#ifndef INT_ARRAY_H_
#define INT_ARRAY_H_

class IntArray
{
    private:
        int *aptr;
        int arraySize;

        void IntArray::subscriptError(const int &);

    public:
        // Exception class - Handles invalid subscripts
        class InvalidSubscript
        {
            private:
                int errSub;

            public:
                InvalidSubscript(const int &errorVal)
                { errSub = errorVal; }

                int getErrSubscript() const
                { return errSub; }
        };

        IntArray(int);
        IntArray(const IntArray &);
        ~IntArray();

        // Accessor function
        int size() const
        { return arraySize; }

        int &operator [](const int &sub);
};

#endif

IntArray.cpp


#include "IntArray.h"

#include <iostream>
using std::cout;

/* **********************************************************
            IntArray::IntArray() - Constructor
    Sets the size of the array and allocates memory for it.
   ********************************************************** */

IntArray::IntArray(int arrSize)
{
    arraySize = arrSize;
    aptr = new int[arrSize];

    for (int count = 0; count < arraySize; count++)
    {
        *(aptr + count) = 0;
    }
}

/* **********************************************************
            IntArray::IntArray() - Copy Constructor
   ********************************************************** */

IntArray::IntArray(const IntArray &obj)
{
    arraySize = obj.arraySize;
    aptr = new int[arraySize];

    for (int count = 0; count < arraySize; count++)
    {
        *(aptr + count) = *(obj.aptr + count);
    }
}

/* **********************************************************
            IntArray::~IntArray() - Destructor
   ********************************************************** */

IntArray::~IntArray()
{
    if (arraySize > 0)
    {
        delete[] aptr;
    }
}

/* **********************************************************
            IntArray::subscriptError() : const int &
    InvalidSubscript is thrown if the value passed to this
    function is invalid.
   ********************************************************** */

void IntArray::subscriptError(const int &sub)
{
    if (sub < 0 || sub >= arraySize)
    {
        throw InvalidSubscript(sub);
    }
}

/* **********************************************************
            IntArray::operator []() : const int &
    The function makes a call to the subscriptError(). If no
    error is thrown, a reference to the element in the array
    indexed by the subscript is returned.
   ********************************************************** */

int &IntArray::operator [](const int &sub)
{
    subscriptError(sub);

    return aptr[sub];
}

IntArrayException.cpp


#include "IntArray.h"

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

/* **********************************************************
                            Function Definitions
   ********************************************************** */

void outputIntro();
void playGame(IntArray &, const int &, const int);
void retrieveValue(IntArray &, const int &, const int);
bool isCorrect(const int &, const int &, const int);

int main()
{
    const int SIZE = 10;
    int         multBy = 0;

    IntArray table(SIZE);

    cout << "MULTIPLICATION GAME\n\n";
    outputIntro();

    cout << "Select a difficulty 1 through " << SIZE << ": ";
    cin >> multBy;

    playGame(table, multBy, SIZE);
    retrieveValue(table, multBy, SIZE);

    cout << "This is the end of the game little Math-Warrior!\n"
          << "You did great! Come and play again!";

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

/* **********************************************************
            outputIntro()
    Outputs an introduction to the game.
   ********************************************************** */

void outputIntro()
{
    cout << "Welcome, little Math-Warrior! In this game you are about to exercise\n"
          << "your multiplication skills. Enter the multiplication number to hone your\n"
          << "superior skills on. If you enter 2, you have to multiply this number by\n"
          << "1 through 10.\n\n";
    cout << "Example: How much is 2 x 5:\n\n";
    cout << "When you are asked, type in the answer you think is correct. If you make\n"
          << "a mistake, you can retry until the answer is correct. You can do it!\n";
    cout << "Have fun, little Math-Warrior!\n\n";
}

/* **********************************************************
            playGame() : obj &, const int &, const int
    The little Math-Warrior is asked to input the result of a
    multiplication. If the answer is correct, the value is
    copied to the array. Otherwise, he or she is asked to
    enter a valid answer. Once all values are entered, a
    congratulatory message is output and the function exits.
   ********************************************************** */

void playGame(IntArray &table, const int &multBy, const int SIZE)
{
    int result = 0;

    cout << "\nMultiplication-Table: " << multBy << "'s\n\n";
    for (int x = 0; x < SIZE; x++)
    {
        cout << "How much is " << (x + 1) << " x " << multBy << ": ";
        cin >> result;

        while (isCorrect(multBy, result, x + 1) == false)
        {
            cout << "\nTry again, little Math-Warrior!\n";
            cout << (x + 1) << " x " << multBy << " is: ";
            cin >> result;
        }

        if (x == SIZE - 1)
        {
            cout << "\nWELL DONE LITTLE MATH WARRIOR YOU BEAT THIS LEVEL!\n";
        }

        table[x] = result;
    }
}

/* **********************************************************
            isCorrect() : const int &, const int &, const int
    This function validates the correctness of the calculation
    result. If it is, true is returned, otherwise false is
    returned.
   ********************************************************** */

bool isCorrect(const int &multBy, const int &result, const int idx)
{
    bool status = false;

    int calc = multBy * idx;

    if (result == calc)
    {
        cout << "WELL DONE!\n\n";
        status = true;
    }

    return status;
}

/* **********************************************************
            retrieveValue() : obj &, const int, const int &
    This function lets our little Math-Warriors do a review.
    He or she is asked to enter the subscript position of the
    array holding the results. If it is correct, the function
    carries out the calculation and outputs the result. If it
    isn't the try/catch block is executed, until a valid
    subscript position has been provided.
   ********************************************************** */

void retrieveValue(IntArray &table, const int &multBy, const int arrSize)
{
    bool tryAgain = true;
    int  subPosition = 0;

    cout << "TIME FOR A REVIEW!\n\n";
    cout << "Enter a number 1 through 10: ";
    cin >> subPosition;

    while (tryAgain)
    {
        try
        {
            cout << "\nThe result of multiplying "
                  << multBy << " x " << subPosition
                  << " is: " << table[subPosition - 1] << "\n\n";
            tryAgain = false;
        }
        catch (IntArray::InvalidSubscript sub)
        {
            cout << "\nThere was an error, little Math-Warrior!\n"
                  << multBy << " x " << sub.getErrSubscript()+1 << " is invalid.\n";
            cout << "This multiplication table goes from 1 through " << arrSize << "\n";
            cout << "Enter a valid number [1 through " << (arrSize) << "]: ";
            cin >> subPosition;
        }
    }
}

Example Output: 







Programming Challenge 16.5 - Total Template

Example File: TotalTemplate.cpp

Notice: Credit for part of the code and special thanks for so kindly providing it goes to 'Ganado.'

TotalTemplate


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

#include <type_traits>
using std::conditional;

#include <typeinfo>
using std::is_same;

template <typename T>
using MyType = typename conditional<is_same<T, unsigned char>::value, int, T>::type;

/* **********************************************************
            template <class T>
    This function lets the user enter a number of values of
    different data types. The only value passed to it is the
    number of values. A running total is kept while the values
    are input, and the total is returned.
   ********************************************************** */

template <class T>
MyType<T> total(int numels)
{
    T value{};
    MyType<T> sumTotal{};
   
    for (; numels > 0; numels--)
    {
        static int count = 1;
   
        cout << "Value #" << count++ << ": ";
        cin >> value;
       
        sumTotal += value;
    }

    return sumTotal;
}

int main()
{
    int numels = 0;

    cout << "TOTAL TEMPLATE DEMO\n\n";
    cout << "This program lets you input any amount of values of\n"
          << "different types of data. For instance int, floating-point\n"
          << "and even characters. Once you finish entering your numbers\n"
          << "or characters, it calculates the total and outputs it.\n\n";

    cout << "Please the number of values you wish to input: ";
    cin >> numels;

    while (numels < 0)
    {
        cout << "Input Error: Enter a valid value!\n";
        cout << "Number of values: ";
        cin >> numels;
    }

    cout << "\nEnter " << numels << " floating-point values\n";
    cout << "\nThe total value is " << total<double>(numels) << "\n\n";

    cout << "Enter " << numels << " integer values\n";
    cout << "\nThe total value is " << total<int>(numels) << "\n\n";

    cout << "Enter " << numels << " characters\n";
    cout << "\nThe total value is " << total<unsigned char>(numels) << "\n\n";

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

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

Example Output:



Tuesday, February 20, 2018

Programming Challenge 16.4 - Absolute Value Template

Example File: AbsoluteValue.cpp

AbsoluteValue.cpp


#include <cmath>
using std::abs;

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

/* **********************************************************
            template <class T>
    This function returns the absolute value of the parameter
    passed to it.
    ********************************************************** */

template <class T>
T absoluteVal(const T &value)
{
    return abs(value);
}

enum MenuOptions { INT = 'I', DOUBLE = 'D', QUIT = 'Q' };

/* **********************************************************
            Function Definitions  
   ********************************************************** */

void outputOptions();
bool isValidInput(char);
void absoluteDouble();
void absoluteInteger();

int main()
{
    char choice = ' ';

    cout << "ABSOLUTE VALUES\n\n";
    cout << "This program finds the absolute value of a number.\n";
    cout << "Example: The absolute value of |-5.7| is 5.7\n\n";

    do
    {
        outputOptions();
        cin >> choice;
        choice = toupper(choice);
       
        while (isValidInput(choice) == false)
        {
            cout << "Choice: ";
            cin >> choice;
            choice = toupper(choice);
        }           

        switch (choice)
        {       
            case DOUBLE:
            {
                absoluteDouble();
            } break;
           
            case INT:
            {
                absoluteInteger();
            } break;       

            case QUIT:
            {
                cout << "\nThank you for trying this program. Have a nice day!";
            } break;
        }
    } while (choice != QUIT);

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

/* **********************************************************
            outputOptions()
    Outputs the menu options to screen.
   ********************************************************** */

void outputOptions()
{
    cout << "Do you wish to enter a floating-point or integer value?\n\n"
          << "'D' - Floating-Point Value\n"
          << "'I' - Integer Value\n"
          << "'Q' - Quit Program\n\n";
    cout << "Choice: ";
}

/* **********************************************************
            isValidInput() : char
    Validates the input and returns true if it is, otherwise
    false is returned.
   ********************************************************** */

bool isValidInput(char choice)
{
    if (choice == INT || choice == DOUBLE || choice == QUIT)
    {
        return true;
    }

    return false;
}

/* **********************************************************
            absoluteDouble()
    The user is asked to enter a floating-point value. The
    value is passed to a template function which returns the
    absolute value. The absolute value is output to screen.
   ********************************************************** */

void absoluteDouble()
{
    double floatingPtVal = 0.0;

    cout << "\nEnter a floating-point value: ";
    cin >> floatingPtVal;

    cout << "The absolute value of |" << floatingPtVal << "|"
          << " is: " << absoluteVal(floatingPtVal) << "\n\n";
}

/* **********************************************************
            absoluteInteger()
    The user is asked to enter an integer value. The value is
    passed to a template function which returns the absolute
    value. The absolute value is output to screen.
   ********************************************************** */

void absoluteInteger()
{
    int integerVal = 0;
    cout << "\nEnter an integer value: ";
    cin >> integerVal;

    cout << "The absolute value of |" << integerVal << "|"
          << " is " << absoluteVal(integerVal) << "\n\n";
}

Example Output:



Monday, February 19, 2018

Programming Challenge 16.3 - Minimum/Maximum Templates

Example File: MinimumMaximum.cpp

MinimumMaximum.cpp


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

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

/* **********************************************************
            template <class Maximum>
    Determines and returns the greater of the two values.
   ********************************************************** */

template <class Maximum>
Maximum greater(const Maximum &valOne, const Maximum &valTwo)
{
    if (valOne > valTwo)
    {
        return valOne;
    }
    else
    {
        return valTwo;
    }
}

/* **********************************************************
            template <class Minimum>
    Determines and returns the smaller of the two values.
   ********************************************************** */

template <class Minimum>
Minimum smaller(const Minimum &valOne, const Minimum &valTwo)
{
    if (valOne < valTwo)
    {
        return valOne;
    }
    else
    {
        return valTwo;
    }
}

void getMaximumVal();
void getMinimumVal();

int main()
{
    char tryAgain = ' ';

    cout << "MINIMUM / MAXIUM\n";
    cout << "Which value is greater, which is less?\n\n";

    do
    {
        getMaximumVal();
        getMinimumVal();

        cout << "Do you wish to try this again? ";
        cin >> tryAgain;

        while (toupper(tryAgain) != 'Y' && toupper(tryAgain) != 'N')
        {
            cout << "Do you wish to try this again? ";
            cin >> tryAgain;
        }
        cout << "\n";
    } while (toupper(tryAgain) != 'N');
   
    cout << "Thank you for trying this program. Have a nice day!\n";

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

/* **********************************************************
            getMaximumVal()
    Asks the user to enter two floating-point values, and two
    characters. These are passed to the template function and
    compared. The highest values are output to screen.
   ********************************************************** */

void getMaximumVal()
{
    double maxDouble = 0.0;
    double maxDoubleOne = 0.0;
    char   maxChar = ' ';
    char   maxCharOne = ' ';

    cout << "Enter two floating-point values: ";
    cin >> maxDouble >> maxDoubleOne;

    cout << "Enter two characters: ";
    cin >> maxChar >> maxCharOne;

    cout << setw(26) << left << "\nThe greater value is:   "
          << greater(maxDouble, maxDoubleOne) << "\n";

    cout << "The greater character is: "
          << greater(maxChar, maxCharOne) << "\n\n";
}

/* **********************************************************
            getMinimumVal()
    The user is asked to enter two integer values, and two
    characters. The values are passed to the template class
    function to determine the minimum value, which is then
    output to screen.
   ********************************************************** */

void getMinimumVal()
{
    int  minInt = 0;
    int  minIntOne = 0;
    char minChar = ' ';
    char minCharOne = ' ';

    cout << "Enter two integer values: ";
    cin >> minInt >> minIntOne;

    cout << "Enter two characters: ";
    cin >> minChar >> minCharOne;

    cout << setw(25) << left << "\nThe lesser value is: "
          << smaller(minInt, minIntOne) << "\n";

    cout << "The lesser character is: "
          << smaller(minChar, minCharOne) << "\n\n";
}

Example Output:



Sunday, February 18, 2018

Programming Challenge 16.2 - Time Format Exceptions

Example Files: TimeFormatException.7z

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"

class MilTime : public Time
{
    protected:
        int milHours;           
        int milSeconds;       

    public:
        // Exception class
        class BadHour
        {
            private:
                int badHour;

            public:
                BadHour(int hourVal) : badHour(hourVal)
                { }

                int getBadHour() const
                { return badHour; }
        };

        // Exception class
        class BadSeconds
        {
            private:
                int badSeconds;

            public:
                BadSeconds(int secondsVal) : badSeconds(secondsVal)
                { }

                int getBadSeconds() const
                { return badSeconds; }
        };

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

        // Constructor
        MilTime(int mHrs, int mSec)
        {
            setTime(mHrs, mSec);       
        }

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

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

#endif

MilTime.cpp


#include "MilTime.h"

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

#include <sstream>
using std::stringstream;

#include <string>
using std::string;

/* **********************************************************
            MilTime::setTime() : const int, const int
    This function sets the values for the milHours and
    milSeconds variables. If the hours value is invalid,
    BadHour is thrown. Otherwise BadSeconds is thrown.
    ********************************************************** */

void MilTime::setTime(const int mHrs, const int mSec)
{
    if (mHrs < 0 || mHrs > 2359 || mHrs % 100 >= 60)
    {
        throw BadHour(mHrs);
    }
    else if (mSec < 0 || mSec > 59)
    {
        throw BadSeconds(mSec);
    }
    else
    {
        milHours = mHrs;
        milSeconds = mSec;

        convertMilTime();
    }
}

/* **********************************************************
            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();
}

TimeFormatException.cpp


#include "MilTime.h"

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

int main()
{
    int  mHrs = 0;
    int  mSecs = 0;
    bool tryAgain = true;

    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";

    while (tryAgain)
    {
        try
        {
            milTimeOne.setTime(mHrs, mSecs);
   
            tryAgain = false;
        }
        catch (MilTime::BadHour hourVal)
        {
            cout << "Error: " << hourVal.getBadHour() << " is no military hour.\n";
            cout << "Hour: ";
            cin >> mHrs;
        }
        catch (MilTime::BadSeconds secondsVal)
        {
            cout << "Error: " << secondsVal.getBadSeconds()
                  << " is an invalid second value.\n";
            cout << "Seconds: ";
            cin >> mSecs;
        }
    }

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

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

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

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

Output:



Programming Challenge 16.1 - Date Exceptions

Example Files: DateExceptions.7z

Date.h


#ifndef DATE_H
#define DATE_H

#include <string>

class Date
{
    private:       
        int month;   
        int day;           
        int year;       

    public:       
        // Exception class
        class InvalidDay
        {
            private:
                int invalidDay;

            public:
                InvalidDay(int dayVal)
                { invalidDay = dayVal; }

                int getInvalidDay() const
                { return invalidDay; }
        };

        // Exception class
        class InvalidMonth
        {
            private:
                int invalidMonth;

            public:
                InvalidMonth(int monthVal)
                { invalidMonth = monthVal; }

                int getInvalidMonth() const
                { return invalidMonth; }
        };
       
        Date();

        // Mutator functions
        void setYear(int);
        bool isLeapYear();
        void setMonth(int);
        void setDay(int);

        // Accessor functions
        void getFormatOne() const;
        void getFormatTwo() const;
        void getFormatThree() const;
};

#endif

Date.cpp


#include "Date.h"

#include <array>
using std::array;

#include <iostream>
using std::cout;

#include <iostream>
using std::string;

// Initializes the daysPerMonth array with the days per month
const array<int, 13> daysPerMonth { 0, 31, 28, 31, 30, 31, 30,
                                    31, 31, 30, 31, 30, 31 };

// Initializes the monthNames array with the names of the months of the year
const array<string, 13> monthNames { "", "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
                                                 "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };

enum Months { JANUARY = 1, FEBRUARY, MARCH, APRIL, MAY, JUNE,
              JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER };

/* **********************************************************
                Date::Date() - Constructor
   ********************************************************** */

Date::Date()
{
    year = 1900;
    month = JANUARY;
    day = 1;
}

/* **********************************************************
            Date::setYear() : int
   This functions sets the value of the year member variable.
    If it is invalid, the year member variable is assigned the
    value 1900.
   ********************************************************** */

void Date::setYear(int yyyy)
{
    if (yyyy >= 0 && yyyy <= 2200)
    {
        year = yyyy;
    }
     else
     {
         year = 1900;
     }
}

/* **********************************************************
            Date::setMonth() : int mm
   This function sets the value of the member variable month.
    InvalidMonth is thrown when an invalid value is passed.
   ********************************************************** */

void Date::setMonth(int mm)
{
    if (mm >= JANUARY && mm <= DECEMBER)
    {
        month = mm;
    }
    else
    {
         throw InvalidMonth(mm);
    }
}

/* **********************************************************
            Date::setDay() : int
    This function sets the value of the member variable day.
    InvalidDay is thrown if an invalid value is passed.
   ********************************************************** */

void Date::setDay(int dd)
{  
    if (month == FEBRUARY && isLeapYear() && dd == 29)
    {
        day = dd;
    }
    else if (dd < 1 || dd > daysPerMonth[month])
    {
        throw InvalidDay(dd);
    }
    else
    {
        day = dd;
    }
}

/* **********************************************************
                Date::isLeapYear (void)
    This function determines whether a year is a leap year. If
    it is true is returned, else false is returned.
   ********************************************************** */

bool Date::isLeapYear()
{
    if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
    {
        return true;
    }

    return false;
}

/* **********************************************************
                Date::displayFormatOne (void)
    This function formats the date as 12/12/2012 and returns
    it.
   ********************************************************** */

void Date::getFormatOne() const
{
    cout << "\nSlash Style:\n";
    cout << month << "/" << day << "/" << year << "\n";
}

/* **********************************************************
                Date::displayFormatTwo (void)
    This function formats the date as DECEMBER 12, 2012 and
    returns it.
   ********************************************************** */

void Date::getFormatTwo() const
{
    cout << "\nU.S. Style:\n";
    cout << monthNames[month] << " " << day << ", " << year << "\n";
}

/* **********************************************************
                Date::displayFormatThree (void)
    This function formats the date as 12 DECEMBER, 2012 and
    returns it.
   ********************************************************** */

void Date::getFormatThree() const
{
    cout << "\nEuropean Style:\n";
    cout << day << " " << monthNames[month] << " " << year << "\n\n";
}

DateDm.cpp


#include "Date.h"

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

int main()
{
   int  month = 0;
   int  day = 0;
   int  year = 0;
    bool tryAgain = true;

    Date dateObj;

   cout << "DATE EXCEPTION DEMO\n\n"
        << "This program lets you enter a date. If it is a valid date,\n"
        << "it is displayed in three formats.\n\n";
    cout << "Please enter a year, a month, and a day (Ex: 2008 02 29): ";
    cin >> year >> month >> day;

    dateObj.setYear(year);

    while (tryAgain)
    {
        try
        {       
            dateObj.setMonth(month);
            dateObj.setDay(day);

            cout << "\nThis is your date in three different formats:\n";
            dateObj.getFormatOne();
            dateObj.getFormatTwo();
            dateObj.getFormatThree();

            tryAgain = false;
        }
        catch (Date::InvalidDay dayVal)
        {
            cout << "\nError: Day " << dayVal.getInvalidDay() << " is invalid.\n";
            cout << "Please enter a valid day: ";
            cin >> day;
        }
        catch (Date::InvalidMonth monthVal)
        {
            cout << "\nError: Month " << monthVal.getInvalidMonth() << " does not exist.\n";
            cout << "Please enter a valid month: ";
            cin >> month;
        }
    }

    cout << "Thank you for trying the Date Exception Demo! Have a nice day!";

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

Example Output: