Thursday, June 22, 2017

[Update] Programming Challenge 12.2

Without being aware of it, the code written for Programming Challenge 12.2 already contained, what was asked for in 12.5: It displayed the line numbers next to whatever text a file contains. That being the case I had to make a decision:

1.) I post a link and explain that, instead of actual code, this is the link to Programming Challenge 12.2 and here is why.
2.) I alter the Programming Challenge 12.2, remove the line that displays the line numbers, take screenshots, update the code, and explain the reason for doing so.

Although I hate to alter code once it is published, it was a good decision this time around. The reason being that there are two example files attached to both Programming Challenges. One contains a long one a short text. In case of the latter it is indeed shorter, yet still contains more than 24 lines of text. I don't even know why, upon testing my program, this went unnoticed. It makes absolutely no sense at all! I can only guess that, originally, it should contain less than 24 lines, to demonstrate that "Press Enter to continue" would not be triggered upon executing the program. Whatever the reason, an updated version of short.txt is online, which now contains less than 24 lines.

Now it is back to my IDE. I wish my visitors, occasional and regular, as well as my fellow learners, to you manage to be productive today, and you, unlike I, don't have to suffer to much under the remorseless heat of summer.

Programming Challenge 12.5 - Line Numbers

Example Files: long.txt
                          short.txt


/* Line Numbers - This is a modification of Programming Challenge 12.2
   The program asks the user for the name of a file. The program displays
    the contents of the file on the screen. Each line of screen output is
    preceded with a line number, followed by a colon. The line numbering
    starts at 1. If the file's contents won't fit on a single screen, the
    program displays 24 lines of output at a time, and then pauses. Each
    time the program pauses, it waits for the user to strike a key before
    the next 24 lines are displayed. */

#include "Utility.h"

void openFile();
bool isGood(fstream &, const string);
void displayText(const vector<string>);

int main()
{
    openFile();

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: openFile

    This function reads in and stores the contents of a text
    file in a vector of string objects.
   ********************************************************** */

void openFile()
{
    string  fileName = " ";            /* To hold the file name */
    string  tmpText = " ";            /* To hold the text         */  
    fstream textFile;                    /* File stream object     */

    vector<string> gamesText;        /* Vector of string objects to hold
                                               the file contents */

    cout << "\n\tLINE NUMBERS\n\n"
         << "\tEnter the name of the file you wish to open: ";
    cin >> fileName;

    if (isGood(textFile, fileName))
    {
        while (getline(textFile, tmpText))
        {
            gamesText.push_back(tmpText);
        }
        textFile.close();

        displayText(gamesText);
    }
    else
    {
        cout << "\tERROR: Cannot open the file.\n"
              << "\tPress Enter or click [X] to exit ...\n";
    }
}

/* **********************************************************
   Definition: isGood

    This function accepts a reference to an fstream object as
    argument. The file is opened for input. The function
    returns true upon success, false upon failure.
   ********************************************************** */

bool isGood(fstream &textFile, const string fileName)
{
    textFile.open(fileName, ios::in);

    if (!textFile.fail())
    {
        return true;
    }
    else
    {
        return false;
    }
}

/* **********************************************************
   Definition: displayText

    This function accepts a vector of string objects as its
    argument. It displays the contents of the string object.
    After every 24 lines of text being output to screen, the
    user is asked to press Enter to continue. If the remaining
    number of lines is less then 24, they are displayed. Else
    the process repeats, until the end of text is reached.
   ********************************************************** */

void displayText(const vector<string> gamesText)
{
    int numLines = 0;

    cout << "\n";
    cin.ignore();

    while (numLines < gamesText.size())
    {
        numLines++;
      
        cout << "\t" << setw(3) << right << numLines << ": "
              << gamesText[numLines-1] << setw(6) << right << "\n";

        if (numLines % 24 == 0)
        {
            cout << "\n\tPress Enter to continue:";
            cin.get();
            cout << "\n";
        }
    }

    if (gamesText.size())
    {
        cout << "\n\tEnd of text.\n"
              << "\tPress Enter to exit this program.";
    }
}

Example Output:






Programming Challenge 12.4 - Tail Program

Example Files: tailLong.txt
                         tailShort.txt


/* Tail Program - This program asks the user for the name of a file.
    The program displays the last 10 lines of the file on the screen
    (the 'tail' of the file). If the file has fewer than 10 lines, the
    entire file is displayed, with a message indicating the entire file
    has been displayed. */

#include "Utility.h"

void menu();
void openFile();
bool isGood(fstream &tail, const string fileName);
void displayText(const vector<string>, const int numLines);

int main()
{
    menu();

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: menu

    This function provides a basic menu. An introduction is
    displayed, and a function to open a file is called. If the
    user wishes, he or she can open another file, or exit the
    program.
   ********************************************************** */

void menu()
{
    char again = ' ';

    cout << "\n\tFILE TAIL PROGRAM\n\n"
          << "\tThis program displays the 'Tail of a file.' This means\n"
          << "\tthat, if a file contains more than 10 lines of text, only\n"
          << "\tthe last 10 lines will be displayed. If it contains fewer\n"
          << "\tthan 10 lines, the full text is displayed.\n\n";

    do
    {
        openFile();

        cout << "\n\tDo you wish to open another file [y/N]? ";
        cin >> again;

        while (toupper(again) != 'Y' && toupper(again) != 'N')
        {
            cout << "\tDo you wish to open another file [y/N]? ";
            cin >> again;
        }

        if (toupper(again) == 'N')
        {
            cout << "\n\tNow exiting the program ...";
        }
    } while (toupper(again) == 'Y');
}

/* **********************************************************
   Definition: openFile

    This function reads in and stores the contents of a text
    file. The contents of the file is stored in a vector of
    strings.
   ********************************************************** */

void openFile()
{
    int     numLines = 0;            /* To hold the number of lines of text */
    string  fileName = " ";           /* To hold the filename */
    string  tmpText = " ";            /* To hold text while it is read-in */
    fstream textFile;                    /* File stream object */

    vector<string> tail;                /* Vector of string objects to hold
                                                the file contents */

    cout << "\nEnter the name of the file you wish to open:\n";
    cin >> fileName;

    if (isGood(textFile, fileName))
    {
        while (getline(textFile, tmpText))
        {
            tail.push_back(tmpText);
            numLines++;       
        }
        textFile.close();

        displayText(tail, numLines);
    }
    else
    {
        cout << "\n\tERROR: Cannot open " << fileName << "\n";
    }
}

/* **********************************************************
   Definition: isGood

    This function accepts a reference to an fstream object as
    argument. The file is opened for input. The function
    returns true upon success, false upon failure.
   ********************************************************** */

bool isGood(fstream &textFile, const string fileName)
{
    textFile.open(fileName, ios::in);

    if (!textFile.fail())
    {
        return true;
    }
    else
    {
        return false;
    }
}

/* **********************************************************
   Definition: displayText

    This function accepts a vector of string objects as its
    argument. If the string object holds more than ten lines
    of text, only the last ten lines are displayed. Else the
    full text, and a message indicating the entire file has
    been displayed, is output to screen.
   ********************************************************** */

void displayText(const vector<string> tail, const int numLines)
{
    size_t index = 0;

    /* This ternary operator determines whether the number of lines
        is greater than 10. If it is, 'index' gets tail.size() - 10,
        or the index position of the 10th from the last line, else it
        gets 0. */
    numLines > 10 ? index = tail.size() -10 : index;

    cout << "\n\n\tFILE TAIL:\n\n";
    for (; index < tail.size(); index++)
    {
        cout << "\t" << tail[index] << "\n";
    }

    if (numLines < 10)
    {
        cout << "\n\tThe entire file has been displayed.\n";
    }
}

Example Output:




Wednesday, June 21, 2017

Programming Challenge 12.3 - Punch Line

Example Files: joke.txt
                         punchline.txt


/* Punch Line - This program reads and prints a joke and its punch line
    from two different files. The first file contains a joke, but not its
    punch line. The second file has the punch line as its last line,
    preceded by 'garbage.' The main function opens the two files and then
    calls two functions, passing each one the file it needs. The first
    function reads and displays each line in the file it is passed (the
    joke file). The second function should display only the last line of
    the file it is passed (the punch line file). It finds this line by
    seeking to the end of the file and then backing up to the beginning
    of the last line. Data to test the program is found in the joke.txt
    and punchline.txt files. */

#include "Utility.h"

void displayJoke(fstream &);
void displayPunchline(fstream &);

int main()
{
    cout << "\n\tJOKE OF THE DAY\n\n";

    fstream joke("joke.txt", ios::in);

    if (joke.fail())
    {
        cout << "\tFile open error. Program aborting now.";
        cin.get();
        return 0;
    }
    else
    {
        displayJoke(joke);
    }
    joke.close();

    fstream pLine("punchline.txt", ios::in);

    if (pLine.fail())
    {
        cout << "\tFile open error. Program aborting now.";
        cin.get();
        return 0;
    }
    else
    {
        displayPunchline(pLine);
    }
    pLine.close();

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: displayJoke

    This function accepts a reference to an fstream object as
    its argument. It reads in text from the 'joke.txt' file,
    and displays its contents.
   ********************************************************** */

void displayJoke(fstream &joke)
{
    string theJoke = " ";

    while (getline(joke, theJoke) && !joke.eof())
    {
        cout << "\t" << theJoke << "\n";
    }
}

/* **********************************************************
    Definition: displayPunchline

    This function accepts a reference to an fstream object as
    its argument. It finds the beginning of the last line in
    the file and displays it.
   ********************************************************** */

void displayPunchline(fstream &pLine)
{
    string punchLine = " ";
    char     tmpChar = ' ';
    long     position = 0;

    pLine.clear();                        /* Rewind the file                 */
    pLine.seekg(0L, ios::end);        /* Move to the end of the file */
   
    /* Starting at -1 bytes relative to the end of the file, this
        loop reads in and processes each character until it finds a
        newline character. If found, the last line in the file is
        read-in and displayed. */
    while (pLine.seekg(position-1, ios::cur))
    {   
        position--;
        pLine.get(tmpChar);

        if (tmpChar == '\n')
        {
            getline(pLine, punchLine);
            cout << "\n\t" << punchLine;
        }
    }       
}

Example Output:





Monday, June 19, 2017

Programming Challenge 12.2 - File Display Program

Example Files: long.txt
                          short.txt


/* File Display Program - This program asks the user for the name of a
    file. The program displays the contents of the file on the screen. If
    the file's contents won't fit on a single screen, the program displays
    24 lines of output at a time, and then pause. Each time the program
    pauses, it waits for the user to strike a key before the next 24 lines
    are displayed. */

#include "Utility.h"

void openFile();
bool isGood(fstream &, const string);
void displayText(const vector<string>);

int main()
{
    openFile();

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: openFile

    This function reads in and stores the contents of a text
    file in a vector of string objects.
   ********************************************************** */

void openFile()
{
    string  fileName = " ";            /* To hold the file name */
    string  tmpText = " ";            /* To hold the text         */  
    fstream textFile;                    /* File stream object     */

    vector<string> gamesText;        /* Vector of string objects to hold
                                               the file contents */

    cout << "\n\tFILE DISPLAY PROGRAM\n\n"
         << "\tEnter the name of the file you wish to open: ";
    cin >> fileName;

    if (isGood(textFile, fileName))
    {
        while (getline(textFile, tmpText))
        {
            gamesText.push_back(tmpText);
        }
        textFile.close();

        displayText(gamesText);
    }
    else
    {
        cout << "\tERROR: Cannot open the file.\n"
              << "\tPress Enter or click [X] to exit ...\n";
    }
}

/* **********************************************************
   Definition: isGood

    This function accepts a reference to an fstream object as
    argument. The file is opened for input. The function
    returns true upon success, false upon failure.
   ********************************************************** */

bool isGood(fstream &textFile, const string fileName)
{
    textFile.open(fileName, ios::in);

    if (!textFile.fail())
    {
        return true;
    }
    else
    {
        return false;
    }
}

/* **********************************************************
   Definition: displayText

    This function accepts a vector of string objects as its
    argument. It displays the contents of the string object.
    After every 24 lines of text being output to screen, the
    user is asked to press Enter to continue. If the remaining
    number of lines is less then 24, they are displayed. Else
    the process repeats, until the end of text is reached.
   ********************************************************** */

void displayText(const vector<string> gamesText)
{
    int numLines = 0;

    cout << "\n";
    cin.ignore();

    while (numLines < gamesText.size())
    {
        numLines++;
      
        cout << "\t" << gamesText[numLines-1] << setw(6) << right << "\n";

        if (numLines % 24 == 0)
        {
            cout << "\n\tPress Enter to continue:";
            cin.get();
            cout << "\n";
        }
    }

    if (gamesText.size())
    {
        cout << "\n\tEnd of text.\n"
              << "\tPress Enter to exit this program.";
    }
}

Example Output:







Programming Challenge 12.1 - File Head Program

Example files: games.txt
                         excerpt.txt


/* File Head Program - This program asks the user for the name of a
    file. The program displays the first 10 lines of the file on the
    screen (the "head" of the file). If the file has fewer than 10
    lines, the entire file is displayed, with a message indicating
    the entire file has been displayed. */

#include "Utility.h"

void menu();
void openFile();
bool isGood(fstream &, const string);
int  lineCnt(const vector<string>);
void displayText(const vector<string>, const int);

int main()
{
    menu();

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: openFile

    This function provides a basic menu. An introduction is
    displayed, and a function to open a file is called. If the
    user wishes, he or she can open another file, or exit the
    program.
   ********************************************************** */

void menu()
{
    char again = ' ';

    cout << "\n\tFILE HEAD PROGRAM\n\n"
            << "\tThis program displays the 'Head of a file.' This means\n"
            << "\tthat, if a file contains more than 10 lines of text, only\n"
            << "\t10 lines will be displayed. If it contains fewer than 10\n"
            << "\tlines, the full text is displayed.\n\n";

    do
    {
        openFile();

        cout << "\n\tDo you wish to open another file [y/N]? ";
        cin >> again;

        if (toupper(again) == 'N')
        {
            cout << "\n\tNow exiting the program ...";
        }
    } while (toupper(again) == 'Y');

}

/* **********************************************************
   Definition: openFile

    This function reads in and stores the contents of a text
    file. The contents of the file is stored in a vector of
    strings.
   ********************************************************** */

void openFile()
{
    int     numLines = 0;            /* To hold the number of lines of text */
    string  fileName = " ";           /* To hold the filename */
    string  tmpText = " ";            /* To hold text while it is read-in */
    fstream textFile;                    /* File stream object */

    vector<string> gamesText;        /* To hold the file contents */

    cout << "\n\tEnter the name of the file you wish to open: ";
    cin >> fileName;

    /* Upon success, the files contents is read in and stored in the vector,
       the number of lines is counted, the file closed, and the displayText
        function is called. In case of an error, a message is displayed, and
        the program will exit. */
    if (isGood(textFile, fileName))
    {
        while (getline(textFile, tmpText) && !textFile.eof())
        {
            gamesText.push_back(tmpText);
            numLines++;
        }
        textFile.close();

        displayText(gamesText, numLines);
    }
    else
    {
        cout << "\tERROR: Cannot open the file.\n\n";
    }
}

/* **********************************************************
   Definition: isGood

    This function accepts a reference to an fstream object as
    argument. The file is opened for input. The function
    returns true upon success, false upon failure.
   ********************************************************** */

bool isGood(fstream &textFile, const string fileName)
{
    textFile.open(fileName, ios::in);

    if (!textFile.fail())
    {
        return true;
    }
    else
    {
        return false;
    }
}

/* **********************************************************
   Definition: displayText

    This function accepts a vector of string objects as its
    argument. If the string object holds more than ten lines
    of text, only the first ten lines are displayed. Else the
    full text, and a message indicating the entire file has
    been displayed, is output to screen.
   ********************************************************** */

void displayText(const vector<string> gamesText, const int numLines)
{
    int output = 0;    /* To hold the number of lines to be output */

    /* This ternary operator determines whether the number of
        lines is greater than 10. If it is, 'output' gets 10,
        else it gets numLines. The purpose is to limit the output
        to screen to a maximum of 10 lines of text. */
    numLines > 10 ? output = 10 : output = numLines;

    cout << "\n\n\tFILE HEAD:\n\n";
    for (int index = 0; index < output; index++)
    {
        cout << "\t" << gamesText[index] << "\n";
    }   

    if (numLines < 10)
    {
        cout << "\n\tThe entire file has been displayed.\n\n";
    }
}

Example Output:





Friday, June 16, 2017

Unions Structs Enums - Easy as Goo Pie

This was really an easy chapter for a change. Many things learned from previous chapters have come together here, making the task of writing code for the fifteen Programming Challenges almost a breeze. I can't say that i am totally satisfied with the totality of my work. There was a number of at least three to four Challenges, that, by putting a little more effort into writing code to solve them, the solutions would have turned out to be way better than I feel they are. The reason is this.

In chapter ten, which was all about strings, string objects and C-strings, I wasn't too sure whether it was worth doing it. Much less what good it would be to learn about such things at that point in time. After being done with this chapter, which involved to put into practice some of the techniques learned from this chapter, I know what it was good for.

Programming Challenge 11.8 - Search Function For Customer Accounts is a very good example. It contains numerous string objects holding date, names, addresses etc., crying out loud for some more in-depth input validation. For the date alone, some of my visitors may have visited Programming Challenge 10.19 - Check Writer which includes a header file for validating the dates. That alone makes for at least 200 lines of code. While it might have been possible to use the include file in Challenge 11.8 as well, it would have still been not enough. What with the names? What with upper- and lowercase for names, and changing the case? 

I was seriously considering it for a while, then, ultimately decided against adding another four to five hundred lines of code to cover every possible input or upper-lowercase error. It is pointless to waste time thinking about what could have been. While my wish to write code as complete as possible, sometimes going above and beyond what has been asked for, my will was not strong enough. I reasoned that it is ultimately just a demo, and that it shouldn't matter to me that much. The important point is: as long as the key points are covered, and no logic or other errors are present, and the program is working as expected, everything should be alright. 

Long story short, this is the reason for my dissatisfaction, not only with Challenge 11.8, but also with some of the other solutions. Summarily I can say that this last chapter was a good precursor for classes, which, unfortunately is not what the next chapter is going to be about. Chapter 12 deals with Advanced File Handling, which I feel will be utmost useful to learn about. 

This being a very small chapter summary, as there really is not much to write about that I can think of, I can't wait for things to come, my knowledge to grow and the weather to become more 'Sitting-In-Front-Of-PC-Trying-To-Write-Code' compatible. With this I wish all of my regular readers, visitors, and of course my fellow learners a good morning, start into your coding day, or a very good rest for the night, after hours in front of your PC, trying to write good code.

Thursday, June 15, 2017

Programming Challenge 11.15 - Multipurpose Payroll

/* Multipurpose Payroll - This program calculates the pay for either an
   hourly paid worker or a salaried worker. Hourly paid workers are paid
    their hourly pay rate times the number of hours worked. Salaried workers
    are paid their regular salary plus any bonus they may have earned. The
    program declares two structures for the following data:

        * Hourly Paid                                        * Salaried
          HoursWorked                                          Salary
          HourlyRate                                          Bonus

    The program also declares a union with two members. Each member is a
    structure variable: one for the hourly paid worker and another for the
    salaried worker.

    The program asks the user whether he or she is calculating the pay for
    an hourly paid worker or a salaried worker. Regardless of which the user
    selects, the appropriate members of the union will be used to store the
    data that will be used to calculate the pay.

    Input Validation: No negative numbers are accepted. No values greater
    than 80 for HoursWorked are accepted. */

#include "Utility.h"

struct HourlyPaid
{
    int    hoursWorked;        /* Number of hours worked */
    double hourlyRate;        /* The hourly pay rate      */
};

struct Salaried
{
    double salary;                /* The employee's salary   */
    double bonus;                /* Bonus for overtime work */
};

union EmployeeType
{
    HourlyPaid worker;        /* HourlyPaid structure variable */
    Salaried staffMember;    /* Salaried structure variable   */
};

void menu();
void getHourlyPaid(EmployeeType &);
void getSalaried(EmployeeType &);
void calcHourlyGP(EmployeeType);
void calcSalariedGP(EmployeeType);

int main()
{
    menu();

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: menu

    This function offers a basic menu from which the user is
    asked to enter data either an hourly employed worker or a
    staff member. Once finished entering data for one of the
    employee types, the user can either repeat the process for
    another employee, or to quit the program.
   ********************************************************** */

void menu()
{
    EmployeeType employee;

    char payType = ' ';
    char next = ' ';
   
    do
    {
        cout << "\n\n\tOnigiri House - Payroll System\n\n\n"
              << "\tEnter employee type:\n\n"
              << "\t[H] for hourly paid workers\n"
              << "\t[S] for salaried employees\n\n"
              << "\tPay Type: ";
        cin >> payType;

        payType = toupper(payType);

        while (payType != 'H' && payType != 'S')
        {
            cout << "\tPay Type: ";
            cin >> payType;
        }

        if (payType == 'H')
        {
            getHourlyPaid(employee);
            calcHourlyGP(employee);
        }
        else
        {
            getSalaried(employee);
            calcSalariedGP(employee);
        }

        cout << "\n\n\tSelect\n\n"
              << "\t[N] for Next employee\n"
              << "\t[Q] to Quit\n"
              << "\n\tEnter Choice: ";
        cin >> next;

        next = toupper(next);

        while (next != 'N' && next != 'Q')
        {
            cout << "\n\n\tSelect\n\n"
                  << "\t[N] for Next employee\n"
                  << "\t[Q] to Quit\n"
                  << "\n\tEnter Choice: ";
            cin >> next;

            next = toupper(next);
        }

        if (next == 'Q')
        {
            cout << "\n\tOnigiri House - Your number one address for Onigiri, "
                     "Bento & Miso Soup\n\n";
        }
    } while (next != 'Q');
}

/* **********************************************************
    Definition: getHourlyPaid

   This function accepts a union as argument. It asks the
    user for the hours worked and the hourly pay rate. This
    information is stored in the appropriate member of the
    EmployeeType union.
   ********************************************************** */

void getHourlyPaid(EmployeeType &hourlyEmp)
{
    double grossPay = 0.0;

    cout << "\n\n\tHourly Paid Employee\n\n"
              "\tEnter number of hours worked:" << setw(7) << right << " ";
    cin >> hourlyEmp.worker.hoursWorked;

    while (hourlyEmp.worker.hoursWorked <= 0 || hourlyEmp.worker.hoursWorked > 80)
    {
        cout << "\tEnter number of hours worked:" << setw(7) << right << " ";
        cin >> hourlyEmp.worker.hoursWorked;
    }

    cout << "\tEnter the hourly pay rate:" << setw(5) << right << "$"
          << setw(2) << right << " ";
    cin >> hourlyEmp.worker.hourlyRate;

    while (hourlyEmp.worker.hourlyRate <= 0)
    {
        cout << "\tEnter the hourly pay rate:" << setw(5) << right << "$"
              << setw(2) << right << " ";
        cin >> hourlyEmp.worker.hourlyRate;
    }
}

/* **********************************************************
   Definition: calcHourlyGP

    This function accepts a union as argument. It calculates
    the weekly gross pay for an hourly employed worker. The
    weekly gross pay is calculated and displayed.
   ********************************************************** */

void calcHourlyGP(EmployeeType hourlyEmp)
{
    double grossPay = 0.0;

    grossPay = (hourlyEmp.worker.hoursWorked * hourlyEmp.worker.hourlyRate);

    cout << fixed << showpoint << setprecision(2);
    cout << "\tWeekly Gross Pay:" << setw(15) << right << "$ " << grossPay << "\n";
}

/* **********************************************************
   Definition: getSalaried

    This function accepts a union as argument. The user is
    asked to enter the annual salary for a staff member. This
    information is stored in the appropriate member of the
    EmployeeType union.
   ********************************************************** */

void getSalaried(EmployeeType &salariedEmp)
{
    cout << "\n\n\tSalaried Employee\n\n"
          << "\tEnter the employee's salary:" << setw(6) << right << "$ ";
    cin >> salariedEmp.staffMember.salary;

    while (salariedEmp.staffMember.salary <= 0)
    {
        cout << "\tEnter the employee's annual salary:" << setw(6) << right << "$ ";
        cin >> salariedEmp.staffMember.salary;
    }
}

/* **********************************************************
   Definition: calcSalariedGP

    This function accepts a union as argument. The weekly
    gross pay for a salaried worker is calculated. Depending
    on the annual wage, a bonus is calculated and added to the
    salary. The weekly gross pay is displayed.
   ********************************************************** */

void calcSalariedGP(EmployeeType salariedEmp)
{
    double grossPay = 0.0;

    salariedEmp.staffMember.salary >= 15000.0 && salariedEmp.staffMember.salary <= 19999.0 ?
    salariedEmp.staffMember.bonus = salariedEmp.staffMember.salary * .15 :
    salariedEmp.staffMember.salary >= 20000.0 && salariedEmp.staffMember.salary <= 29999.0 ?
    salariedEmp.staffMember.bonus = salariedEmp.staffMember.salary * .20 :
    salariedEmp.staffMember.salary >= 30000.0 && salariedEmp.staffMember.salary <= 49999.0 ?
    salariedEmp.staffMember.bonus = salariedEmp.staffMember.salary * .30 :
    salariedEmp.staffMember.bonus = salariedEmp.staffMember.salary * .50;

    grossPay = (salariedEmp.staffMember.bonus + salariedEmp.staffMember.salary) / 52;

    cout << fixed << showpoint << setprecision(2);
    cout << "\tWeekly Gross Pay:" << setw(17) << right << "$ " << grossPay << "\n";
}

Example Output:





Programming Challenge 11.14 - Inventory Bins

Include File: UtilityCls.h


/* Inventory Bins - This program simulates inventory bins in a warehouse.
    Each bin holds a number of the same type of parts. The program uses a
    structure that keeps the following data:
   
        * Description of the part kept in the bin
        * Number of parts in the bin

    The program has an array of 10 bins, initialized with the following
    data:

        * Part Description                Number of Parts in the Bin
          --------------------                 ---------------------------------
          Valve                                                                          10
          Bearing                                                                         5
          Bushing                                                                      15
          Coupling                                                                     21
          Flange                                                                           7
          Gear                                                                              5
          Gear Housing                                                                5
          Vacuum Gripper                                                          25
          Cable                                                                           18
          Rod                                                                              12

    The program has the following functions:

        * AddParts:            A function that increases a specific bin's part
                                count by a specified number.
        * RemoveParts:        A function that decreases a specific bin's part
                                count by a specified number.

    When the program runs, it repeats a loop that performs the following
    steps: The user sees a list of what each bin holds and how many parts
    are in each bin. The user can choose to either quit the program or
    select a bin. When a bin is selected, the user can either add parts to
    it or remove parts from it. The loop then repeats, showing the updated
    bin data on the screen.

    Input validation: No bin can hold more than 30 parts, so the user is
    not allowed to add more than a bin can hold. Also, no negative values
    for the number of parts being added or removed are allowed. */

#include "UtilityCls.h"

struct InventoryBin
{
    string partDesc;        /* Inventory bin part description         */
    int    numParts;        /* Number of parts in the invetory bins */

    InventoryBin(string pD = "N/A", int nP = 30)
    {
        partDesc = pD;
        numParts = nP;
    }

    ~InventoryBin()
    {
    }
};

enum options
{
    ADD_PARTS = 1, REMOVE_PARTS = 2, QUIT = 3
};

void menu(InventoryBin[], const int);
void displayBins(InventoryBin [], const int);
int  getBinID(const int);
void addParts(InventoryBin [], const int, const int, const int);
void removeParts(InventoryBin [], const int, const int, const int);

int main()
{
    const int BINS = 10;


    InventoryBin invBins[BINS] = { { "Valve",               10 },    { "Bearing",           5 },
                                                          { "Bushing",           15 },   { "Coupling",         21 },
                                                          { "Flange",          7 },         { "Gear",            5 },
                                                          { "Gear Housing",    5 },    { "Vacuum Gripper", 25 },
                                                          { "Cable",          18 },         { "Rod",            12 } };

    menu(invBins, BINS);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: menu

    This function accepts an array of structures as argument.
    It acts as a menu from which all the other functions are
    called.
   ********************************************************** */

void menu(InventoryBin invBins[], const int BINS)
{
    const int MAX_PARTS = 30;
    const int MIN_PARTS = 0;
    int selection = 0;
    int binID = 0;

    displayBins(invBins, BINS);

    do
    {
   
      cout << "\n\tSelect [1] to add items\n"
            << "\tSelect [2] to remove items\n"
            << "\tSelect [3] to quit\n\n"
            << "\tSelect: ";
      cin >> selection;

      while (selection < ADD_PARTS || selection > QUIT)
      {
          cout << "\tSelect: ";
          cin >> selection;
      }

      switch (selection)
      {
          case ADD_PARTS:
          {
              binID = getBinID(BINS);

              if (invBins[binID].numParts != MAX_PARTS)
              {
                  addParts(invBins, binID, MAX_PARTS, BINS);
              }
             clearScreen();
            displayBins(invBins, BINS);
          } break;

          case REMOVE_PARTS:
          {
                binID = getBinID(BINS);

                if (invBins[binID].numParts != MIN_PARTS)
                {
                    removeParts(invBins, binID, MIN_PARTS, BINS);
                }
                clearScreen();
                displayBins(invBins, BINS);
          } break;

          case QUIT:
          {
              cout << "\n\tMARAVILHOSO Warehouse - 'Experience is the mother of wisdom'";
          }
      }
    } while (selection != QUIT);
}

/* **********************************************************
   Definition: displayBins

    This function accepts an array of structures as argument.
    It displays the contents of the array of structures.
   ********************************************************** */

void displayBins(InventoryBin invBins[], const int BINS)
{
    cout << "\n\t\t    MARAVILHOSO Warehouse - Inventory\n\n\n"
         << "\tBin\t    Part Description"
          << setw(31) << right << "Number of parts\n\n";

    for (int index = 0; index < BINS; index++)
    {
        cout << "\t";
        cout << setw(12) << left << (index + 1)
              << setw(15) << left  << invBins[index].partDesc
              << setw(30) << right << invBins[index].numParts << "\n";
    }
}

/* **********************************************************
   Definition: getBinID

    This function asks the user to enter the bin number he or
    she wishes to change. This number is returned from the
    function.
   ********************************************************** */

int getBinID(const int BINS)
{
    int binID = 0;

    cout << "\n\tEnter Bin Number: ";
    cin >> binID;

    while (binID < 1 || binID > BINS)
    {
        cout << "\n\tEnter Bin Number: ";
        cin >> binID;
    }

    return binID -= 1;
}

/* **********************************************************
   Definition: addParts

    This function accepts an array of structures as argument.
    It allows the user to enter the number of inventory parts
    he or she wishes to add to a bin previously selected. The
    user is only able to enter numbers as long as the number
    of items is not greater than the maximum number of parts
    a bin can hold. He or she is also unable to enter negative
    numbers for items to add.
   ********************************************************** */

void addParts(InventoryBin invBins[], const int selection,
                  const int MAX_PARTS, const int BINS)
{
    int add = 0;

    cout << "\n\tEnter number of parts to add: ";
    cin >> add;

    while (add < 0)
    {
        cout << "\tEnter number of parts to add: ";
        cin >> add;
    }

    while (invBins[selection].numParts + add > MAX_PARTS)
    {
        cout << "\n\tMaximum Part Number 30 items\n\n"
              << "\tEnter number of parts: ";
        cin >> add;
    }

    if (invBins[selection].numParts + add <= MAX_PARTS)
    {
        invBins[selection].numParts += add;
    }
}

/* **********************************************************
   Definition: removeParts

    This function accepts an array of structures as argument.
    It allows the user to enter the number of inventory parts
    he or she wishes to remove from a bin previously selected.
    The user is only able to enter numbers as long as the
    number of items is not less than 0. He or she is also
    unable to enter negative numbers for items to remove.
   ********************************************************** */

void removeParts(InventoryBin invBins[], const int selection,
                      const int MIN_PARTS, const int BINS)
{
   int remove = 0;

    cout << "\n\tEnter number of parts to remove: ";
    cin >> remove;

    while (remove < 0)
    {
        cout << "\tEnter number of parts to remove: ";
        cin >> remove;
    }

    while (invBins[selection].numParts - remove < MIN_PARTS)
    {
        cout << "\n\tToo many parts selected\n\n"
              << "\tEnter number of parts to remove: ";
        cin >> remove;
    }

    if (invBins[selection].numParts - remove >= MIN_PARTS)
    {
        invBins[selection].numParts -= remove;
    }
}

Example Output:








Wednesday, June 14, 2017

Programming Challenge 11.13 - Drink Machine Simulator

Include File: UtilityCls.h


/* Drink Machine Simulator - This program simulates a soft drink machine.
    The program uses a structure that stores the following data:
   
        * Drink Name
        * Drink Cost
        * Number of Drinks in Machine

    The program creates an array of five structures. The elements are
    initialized with the following data:

        * Drink Name                    Cost                    Number in Machine
          ----------------                    -----                     ------------------------
          Cola                                    .75                                                20
          Root Beer                            .75                                               20
          Lemon-Lime                       .75                                               20
          Grape Soda                         .80                                                20
          Cream Soda                        .80                                                20
   
    Each time the program runs, it enters a loop that performs the following
    steps: A list of drinks is displayed on the screen. The user is allowed
    to either quit the program or pick a drink. If the user selects a drink,
    he or she will next enter the amount of money that is to be inserted into
    the drink machine. The program displays the amount of change that would be
    returned and subtract one from the number of that drink left in the machine.
    If the user selects a drink that has sold out, a message is displayed. The
    loop then repeats. When the user chooses to quit the program it displays the
    total amount of money the machine earned.

    Input Validation: When the user enters an amount of money, no negative values
    or values greater than $1.00 are accepted. */

#include "UtilityCls.h"

struct Hanbaiki
{
    string drinkName;        /*    Name of the drinks */
    double cost;             /* Product price         */
    int    numDrinks;        /* Number of drinks   */

    Hanbaiki(string d = "N/A", double c = 0.0, int n = 20)
    {
        drinkName = d;
        cost = c;
        numDrinks = n;
    }

    ~Hanbaiki()
    {
    }
};

struct Sales
{
    double revenue;            /* Gets the revenue                                            */
    double change;                /* Holds the change                                            */                                   
    double numAvailable;        /* Keeps track of the available drinks                    */
    double sumInserted;        /* Gets the amount inserted into the coin receiver */

    Sales(double rv = 0.0, double sm = 0.0, double chg = 0.0, int av = 0)
    {
        revenue = rv;
        change = chg;
        sumInserted = sm;
        numAvailable = av;
    }

    ~Sales()
    {
    }
};

enum hanbaikiMenu
{
    BUY = 1, CANCEL = 2, QUIT = 3
};

enum drinks
{
    COLA = 0, ROOT_BEER = 1, LEMON_LIME = 2, GRAPE_SODA = 3, CREAM_SODA = 4
};

enum acceptedCoins
{
    FIVE_CT = 1, TEN_CT = 2, TWENTYFIFE_CT = 3, FIFTY_CT = 4, ONE_DOLLAR = 5
};

void menu(Hanbaiki *, Sales, const int);
int  getOption();
void displayDrinks(Hanbaiki *, const int);
void calcRevenue(Hanbaiki *, Sales &, const int, const int);
int  getCoins();
void coinReceiver(Hanbaiki *, Sales, const int, const int);
bool reqRefill(Hanbaiki *, Sales, const int);

int main()
{
    const int PRODUCTS = 5;

    Sales rev;

    Hanbaiki drinks[PRODUCTS] = { { "COLA",         0.75 },
                                            { "ROOT BEER",  0.75 },
                                            { "LEMON LIME", 0.75 },
                                            { "GRAPE SODA", 0.80 },
                                            { "CREAM SODA", 0.80 } };

    menu(drinks, rev, PRODUCTS);

   return 0;
}

/* **********************************************************
   Definition: menu

    This function accepts an array of structs and a structure
    as argument. It acts as the main menu from which all other
    functions are called.
   ********************************************************** */

void menu(Hanbaiki *drinks, Sales rev, const int PRODUCTS)
{
    int  selection = 0;
    int  option = 0;
    bool isEmpty = false;

    do
    {
        cout << fixed << showpoint << setprecision(2);
        cout << "\n\tSUNTORY Soft Drinks\n\n";

        displayDrinks(drinks, PRODUCTS);
       
        cout << "\n\n\tSelect [0 = Cancel | Options]: ";
        cin >> selection;

        if (selection == 0)
        {
            option = getOption();
        }
        else
        {
            selection -= 1;

            while (selection < COLA || selection > CREAM_SODA)
            {
                cout << "\n\tSelect [0 = Cancel | Options]: ";
                cin >> selection;

                selection -= 1;
            }

            option = getOption();
        }

        switch (option)
        {
            case BUY:
            {               
                if (drinks[selection].numDrinks != 0 && option != CANCEL)
                {
                    coinReceiver(drinks, rev, selection, PRODUCTS);
                    pauseSystem();
                    clearScreen();
                    calcRevenue(drinks, rev, selection, PRODUCTS);
                }
                else
                {
                    clearScreen();
                }

                if (isEmpty = reqRefill(drinks, rev, PRODUCTS))
                {
                    cout << fixed << showpoint << setprecision(2);
                   cout << "\n\n\tVENDING MACHINE EMPTY\n\n"
                          << "\tPlease call SUNTORY: 0421-5884929\n\n"
                         << "\tSUNTORY - Your number one in Soft Drinks\n\n"
                         << "\tTotal Revenue: " << rev.revenue << " $\n";

                    option = 3;
                    pauseSystem();
                }
            } break;

            case CANCEL:
            {
                clearScreen();
            } break;

            case QUIT:       
            {
                cout << "\n\n\tSUNTORY - Your number one in Soft Drinks\n\n";
                cout << "\tTotal Revenue: " << rev.revenue << " $\n";

                pauseSystem();
            } break;
        }
    } while (option != QUIT);
}

/* **********************************************************
   Definition: getOption

    This function asks the buyer to select from the following
    options:

        * BUY            To buy a drink
        * CANCEL        To cancel the transaction
        * QUIT        To exit the program

    The selection is returned from the function.
   ********************************************************** */

int getOption()
{
    int option = 0;

    cout << "\n\t1: BUY"
          << "\n\t2: CANCEL"
          << "\n\t3: QUIT\n\n"
          << "\tOption: ";
    cin >> option;

    while (option < BUY || option > QUIT)
    {
        cout << "\n\tOption: ";
        cin >> option;
    }

    return option;
}

/* **********************************************************
   Definition: displayDrinks

    This function accepts an array of structs as argument. It
    displays a list of drinks, their names, price and the
    number of available products. If the number of drinks is
    0, 'OUT OF STOCK' is output.
   ********************************************************** */

void displayDrinks(Hanbaiki *drinks, const int PRODUCTS)
{   
        cout << "\t[  1  ] "          << drinks[COLA].drinkName
              << setw(23) << right << drinks[COLA].cost;
   
        drinks[COLA].numDrinks > 0 ? cout << setw(23) << right
                                                     << "Drinks Left: " << drinks[COLA].numDrinks :
                                              cout << setw(24) << right << "OUT OF STOCK";
   
        cout << "\n\t[  2  ] "      << drinks[ROOT_BEER].drinkName
              << setw(18) << right << drinks[ROOT_BEER].cost;
   
        drinks[ROOT_BEER].numDrinks > 0 ? cout << setw(23) << right << "Drinks Left: "
                                                           << drinks[ROOT_BEER].numDrinks :
                                                     cout << setw(24) << right << "OUT OF STOCK";

        cout << "\n\t[  3  ] "      << drinks[LEMON_LIME].drinkName
              << setw(17) << right << drinks[LEMON_LIME].cost;         

        drinks[LEMON_LIME].numDrinks > 0 ? cout << setw(23) << right << "Drinks Left: "
                                                             << drinks[LEMON_LIME].numDrinks :
                                                      cout << setw(24) << right << "OUT OF STOCK";

        cout << "\n\t[  4  ] "      << drinks[GRAPE_SODA].drinkName
              << setw(17) << right << drinks[GRAPE_SODA].cost;

        drinks[GRAPE_SODA].numDrinks > 0 ? cout << setw(23) << right << "Drinks Left: "
                                                             << drinks[GRAPE_SODA].numDrinks :
                                                      cout << setw(24) << right << "OUT OF STOCK";

        cout << "\n\t[  5  ] "      << drinks[CREAM_SODA].drinkName
              << setw(17) << right << drinks[CREAM_SODA].cost;

        drinks[CREAM_SODA].numDrinks > 0 ? cout << setw(23) << right << "Drinks Left: "
                                                             << drinks[CREAM_SODA].numDrinks :
                                                      cout << setw(26) << right << "OUT OF STOCK\n\n";
}

/* **********************************************************
    Definition: coinReceiver

    This function accepts an array of structs and a structure
    as arguments. It acts as coin receiver. It keeps track of
    the amount of money inserted, which is constantly updated
    and displayed. If the amount of money received is greater
    than the product cost, the change is calculated, and the
    amount a buyer would normally receive is displayed.
    ********************************************************** */

void coinReceiver(Hanbaiki *drinks, Sales rev, const int selection,
                       const int PRODUCTS)
{
    const double coins[5] = { .05, .10, .25, .50, 1.0 };

    int insert = 0;

    do
    {
        insert = getCoins();

        if (rev.sumInserted < drinks[selection].cost)
        {
            cout << "\n\tYou inserted: " << (rev.sumInserted += coins[insert - 1]) << "\n";

            if (rev.sumInserted > drinks[selection].cost)
            {
                rev.change = rev.sumInserted - drinks[selection].cost;
                rev.sumInserted = drinks[selection].cost;

                cout << "\n\tChange: " << rev.change << " ct.\n";
            }           
        }
    } while (drinks[selection].cost != rev.sumInserted);
}

/* **********************************************************
   Definition: getCoins

    This function displays a list of coins the buyer is asked
    to insert. The lowest amount being five cents, the highest
    one dollar. The selection is returned.
   ********************************************************** */

int getCoins()
{
    int insert = 0;

    cout << "\n\t[ 1. ]" << setw(12) << right <<  "5 ct.\n"
          << "\t[ 2. ]"   << setw(12) << right << "10 ct.\n"
          << "\t[ 3. ]"   << setw(12) << right << "25 ct.\n"
          << "\t[ 4. ]"   << setw(12) << right << "50 ct.\n"
          << "\t[ 5. ]"   << setw(13) << right << " 1  D.\n\n";
    cout << "\tInsert: ";
    cin >> insert;

    while (insert < FIVE_CT || insert > ONE_DOLLAR)
    {
        cout << "\tInsert: ";
        cin >> insert;
    }

    return insert;
}

/* **********************************************************
    Definition: calcRevenue

    This function accepts an array of structs, a structure
    as argument. It calculates the revenue and stores it in
    the appropriate member of the Sales structure. It also
    deducts 1 from the number of available drinks after a
    sale has taken place.
    ********************************************************** */

void calcRevenue(Hanbaiki *drinks, Sales &rev, const int selection,
                      const int PRODUCTS)
{
    rev.revenue += drinks[selection].cost;

    drinks[selection].numDrinks -= 1;
}

/* **********************************************************
   Definition: reqRefill

    This function accepts an array of structs and a structure
    as arguments. It keeps track of the total number of drinks
    which is stored in the appropriate member of the Sales
    structure. This information is returned from the function.
   ********************************************************** */

bool reqRefill(Hanbaiki *drinks, Sales rev, const int PRODUCTS)
{
    bool isEmpty = false;

    for (int index = 0; index < PRODUCTS; index++)
    {
        rev.numAvailable += drinks[index].numDrinks;
    }

    if (rev.numAvailable == 0)
    {
        isEmpty = true;
    }

    return isEmpty;
}

Example Output: