Saturday, June 10, 2017

Programming Challenge 11.12 - Course Grade

/* Course Grade - This program uses a structure to store the following data:
   
        * Name                                    Student name
        * Idnum                                   Student ID number
        * Tests                                     Pointer to an array of test scores
        * Average                                Average test score
        * Grade                                   Course grade
   
    The program keeps a list of test scores for a group of students. It asks
    the user how many test scores there are to be and how many students there
    are. It then dynamically allocates an array of structures. Each structure's
    Tests member points to a dynamically allocated array that holds the test
    scores.

    After the arrays have been dynamically allocated, the program asks for the
    ID number and all the test scores for each student. The average test score
    is calculated and stored in the average member of each structure. The course
    grade is computed on the basis of the following grading scale:

        * Average Test Grade                    Course Grade
          91-100                                         A
          81-90                                           B
          71-80                                           C
          61-70                                           D
          60 or below                                 F

    The course grade is then stored in the Grade member of each structure. Once
    all this data is calculated, a table is displayed on the screen listing each
    student's name, ID number, average test score, and course grade.

    Input Validation: It is ensured that all data for each student is entered.
    No negative numbers for any test score are accepted. */

#include "Utility.h"

struct CourseGrade
{
    string name;                /* Student name                              */
    int    IdNum;                /* Student's ID number                      */
    int   *testScores;        /* Pointer to an array of test scores */
    double average;            /* Student's average test score          */   
    char     grade;                /* Student's letter grade                  */

    ~CourseGrade()              /* Destructor */
    {
        delete testScores;
        testScores = nullptr;
    }
};

enum letterGrades
{
    A = 0, B = 1, C = 2, D = 3, F = 4
};

void initStudents(CourseGrade *, const int, const int);
void getScores(CourseGrade *, const int, const int);
void calcAvgScore(CourseGrade *, const int, const int);
void assignGrade(CourseGrade *, const int);
void displayRepCard(const CourseGrade *, const int);
void freeMem(CourseGrade *);

int main()
{
    CourseGrade *students = nullptr;

    int numStudents = 0;
    int numTests = 0;

    cout << "\n\tGaborone - Rainbow Secondary School "
          << "Gradebook\n\n\n"
          << "\tGrade Entry\n\n";
    cout << "\tHow many students are in your class? ";
    cin >> numStudents;
   
    cout << "\tHow many tests have been written?    ";
    cin >> numTests;

    students = new CourseGrade[numStudents]();

    initStudents(students, numStudents, numTests);
    getScores(students, numStudents, numTests);
    calcAvgScore(students, numStudents, numTests);
    assignGrade(students, numStudents);
    displayRepCard(students, numStudents);
    freeMem(students);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: initStudents

    This function accepts a dynamically allocated array of
    structs as argument. It causes each each student's
    testScores member to point to a dynamically allocated
    array that holds the student's test scores.
   ********************************************************** */

void initStudents(CourseGrade *students, const int numStudents,
                        const int numTests)
{
    for (int index = 0; index < numStudents; index++)
    {
        students[index].testScores = new int[numTests]();
    }
}

/* **********************************************************
   Definition: getScores

    This function accepts a dynamically allocated array of
    structs as argument. It asks the user to enter the name of
    each student, his or her student ID and the scores for a
    number of tests. This input is stored in the appropriate
    members of the CourseGrade structure.
   ********************************************************** */

void getScores(CourseGrade *students, const int numStudents,
                    const int numTests)
{
    for (int studentIdx = 0; studentIdx < numStudents; studentIdx++)
    {
        cout << "\n\tStudent name: ";
        cin.ignore();
        getline(cin, students[studentIdx].name);

        /* Verifies that the name struct member isn't empty */
        while (students[studentIdx].name.empty() ||
                 isblank(students[studentIdx].name[0]) &&
               !isalpha(students[studentIdx+1].name[studentIdx]))
        {
            cout << "\tStudent name: ";
            getline(cin, students[studentIdx].name);
        }

        cout << "\tStudent ID:   ";
        cin >> students[studentIdx].IdNum;

        while (students[studentIdx].IdNum == students[studentIdx - 1].IdNum ||
                 students[studentIdx].IdNum == 0)
        {
            cout << "\n\tStudent ID:   " << students[studentIdx].IdNum
                  << " taken.\n"
                  << "\tStudent ID:   ";
            cin >> students[studentIdx].IdNum;
        }

        for (int blank = 0; blank < 1; blank++)
        {
            cout << "\n";
        }

        for (int testIdx = 0; testIdx < numTests; testIdx++)
        {
            cout << "\tTest score " << (testIdx + 1) << ": ";
            cin >> students[studentIdx].testScores[testIdx];

            /* Validate Input */
            while (students[studentIdx].testScores[testIdx] <= 0 ||
                    students[studentIdx].testScores[testIdx] > 100)
            {
                cout << "\n\tInvalid score!\n"
                      << "\tTest score " << (testIdx + 1) << ": ";
                cin >> students[studentIdx].testScores[testIdx];
            }
        }
    }
}

/* **********************************************************
   Definition: calcAvgScore

    This function accepts a dynamically allocated array of
    structs as argument. It calculates the average score for
    each student, and stores it in the appropriate structure
    member.
   ********************************************************** */

void calcAvgScore(CourseGrade *students, const int numStudents,
                        const int numTests)
{
    for (int studentIdx = 0; studentIdx < numStudents; studentIdx++)
    {
        double total = 0.0;

        for (int testIdx = 0; testIdx < numTests; testIdx++)
        {
            /* Calculate the sum-total of test scores for each student */
            total += students[studentIdx].testScores[testIdx];

            /* Get the average score for each student */
            students[studentIdx].average = total / numTests;
        }
    }
}

/* **********************************************************
   Definition: assignGrade

    This function accepts a dynamically allocated array of
    structs as argument. The nested ternary operator inside
    this function determines the letter grade based on the
    average score achieved by each student. It assigns and
    stores the letter grade to the 'grade' member.
   ********************************************************** */

void assignGrade(CourseGrade *students, const int numStudents)
{
    /* Char array to hold the letter grades */
    const char letterGrades[] = { 'A', 'B', 'C', 'D', 'F' };

    for (int studentIdx = 0; studentIdx < numStudents; studentIdx++)
    {
        students[studentIdx].average > 90 ?   students[studentIdx].grade = letterGrades[A] :
        students[studentIdx].average >= 81 && students[studentIdx].average < 91 ?
                                                         students[studentIdx].grade = letterGrades[B] :
        students[studentIdx].average >= 71 && students[studentIdx].average < 81 ?
                                                          students[studentIdx].grade = letterGrades[C] :
        students[studentIdx].average >= 61 && students[studentIdx].average < 71 ?
                                                          students[studentIdx].grade = letterGrades[D] :
                                                          students[studentIdx].grade = letterGrades[F];     
    }
}

/* **********************************************************
   Definition: displayRepCard

    This function accepts a dynamically allocated array of
    structures as argument. It displays a table on the screen,
    listing each students name, ID, average score and letter
    grade.
   ********************************************************** */

void displayRepCard(const CourseGrade *students, const int numStudents)
{
    cout << "\n\n\tGaborone - Rainbow Secondary School\n\n"
          << "\tSTUDENT REPORT CARD\n\n"
          << "\tStudent Name"
          << setw(25) << right << "Student ID"
          << setw(19) << right << "Average Score"
          << setw(23) << right << "Letter Grade\n";

    cout << "\t" << setw(79) << right << setfill('-') << "\n";
    cout << setfill(' ');

    for (int studentIdx = 0; studentIdx < numStudents; studentIdx++)
    {
        cout << fixed << showpoint << setprecision(2) << "\t";

        cout << setw(25) << left  << students[studentIdx].name
              << setw(12) << right << students[studentIdx].IdNum
              << setw(19) << right << students[studentIdx].average
              << setw(22) << right << students[studentIdx].grade << "\n";
    }
}

/* **********************************************************
   Definition: freeMem

    This function accepts a dynamically allocated array of
    structs as argument. It frees the memory.
   ********************************************************** */

void freeMem(CourseGrade *students)
{
    delete[] students;
    students = nullptr;
}

Example Output:





Thursday, June 8, 2017

Programming Challenge 11.11 - Monthly Budget

/* Monthly Budget - A student has established the following monthly budget:

        * Housing:                      500.00            Utilities:                  150.00
        * Household Expenses:       65.00            Transportation:           50.00
        * Food:                          250.00           Medical:                        30.00
        * Insurance:                  100.00       Entertainment:              150.00
        * Clothing:                       75.00            Miscellaneous:                50.00

    This program has a MonthlyBudget structure designed to hold each of these
    expense categories. The program passes the structure to a function that
    asks the user to enter the amounts spent in each budget category during a
    month. The program then passes the structure to a function that displays a
    report indicating the amount over or under in each category, as well as the
    amount over or under for the entire monthly budget. */

#include "Utility.h"

struct MonthlyBudget
{
    double housing;            /* Amount spent for housing                 */
    double utilities;            /* Amount spent for utilities                 */
    double householdExp;        /* Amount spent for household expenses  */
    double transport;            /* Amount spent for transportation         */
    double food;                /* Amount spent for food                     */
    double medical;            /* Amount spent for medical treatment   */
    double insurance;            /* Amount spent for insurance                 */
    double entertainment;    /* Amount spent for entertainment         */   
    double clothing;            /* Amount spent for clothing                 */
    double miscellaneous;    /* Amount spent for miscellaneous items */
    double total;                /* Total amount spent                         */           
};

void getBudget(MonthlyBudget &);
void calcTotal(MonthlyBudget &);
void calcBudget(const double, const double);
void displayBudget(const MonthlyBudget, const MonthlyBudget);

int main()
{
    MonthlyBudget spentBudget;
    MonthlyBudget fixedBudget = { 500.0, 150.0,  65.0, 50.0, 250.0,
                                            30.0, 100.0, 150.0, 75.0,  50.0, 1420.0 };

    getBudget(spentBudget);
    calcTotal(spentBudget);
    displayBudget(spentBudget, fixedBudget);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: getBudget

    This function asks the user to enter the sum spent for the
    budget items. The input is stored in the appropriate
    structure members.
   ********************************************************** */

void getBudget(MonthlyBudget &spentBudget)
{
    cout << "\n\tMONTHLY BUDGET - EXPENSES\n\n"
          << setw(25) << left << "\tHousing:"
          << setw(3) << right << "$ ";
    cin >> spentBudget.housing;

    while (spentBudget.housing <= 0.0)
    {
        cout << setw(25) << left << "\tHousing:"
             << setw(3) << right << "$ ";
        cin >> spentBudget.housing;
    }
   
    cout << setw(25) << left << "\tUtilities:"
          << setw(3) << right << "$ ";
    cin >> spentBudget.utilities;

    while (spentBudget.utilities <= 0.0)
    {
        cout << setw(25) << left << "\tUtilities:"
              << setw(3) << right << "$ ";
        cin >> spentBudget.utilities;
    }

    cout << setw(25) << left << "\tHousehold Expenses:"
          << setw(3) << right << "$ ";
    cin >> spentBudget.householdExp;

    while (spentBudget.householdExp <= 0.0)
    {
        cout << setw(25) << left << "\tHousehold Expenses:"
              << setw(3) << right << "$ ";
        cin >> spentBudget.householdExp;
    }

    cout << setw(25) << left << "\tTransportation:"
          << setw(3) << right << "$ ";
    cin >> spentBudget.transport;

    while (spentBudget.transport <= 0.0)
    {
        cout << setw(25) << left << "\tTransportation:"
              << setw(3) << right << "$ ";
        cin >> spentBudget.transport;
    }

    cout << setw(25) << left << "\tFood:"
          << setw(3) << right << "$ ";
    cin >> spentBudget.food;

    while (spentBudget.food <= 0.0)
    {
        cout << setw(25) << left << "\tFood:"
              << setw(3) << right << "$ ";
        cin >> spentBudget.food;
    }

    cout << setw(25) << left << "\tMedical:"
          << setw(3) << right << "$ ";
    cin >> spentBudget.medical;
   
    while (spentBudget.medical <= 0.0)
    {
        cout << setw(25) << left << "\tMedical:"
              << setw(3) << right << "$ ";
        cin >> spentBudget.medical;
    }

    cout << setw(25) << left << "\tInsurance:"
          << setw(3) << right << "$ ";
    cin >> spentBudget.insurance;

    while (spentBudget.insurance <= 0.0)
    {
        cout << setw(25) << left << "\tInsurance:"
              << setw(3) << right << "$ ";
        cin >> spentBudget.insurance;
    }

    cout << setw(25) << left << "\tEntertainment:"
          << setw(3) << right << "$ ";
    cin >> spentBudget.entertainment;

    while (spentBudget.entertainment <= 0.0)
    {
        cout << setw(25) << left << "\tEntertainment: "
              << setw(3) << right << "$ ";
        cin >> spentBudget.entertainment;
    }

    cout << setw(25) << left << "\tClothing:"
          << setw(3) << right << "$ ";
    cin >> spentBudget.clothing;

    while (spentBudget.clothing <= 0.0)
    {
        cout << setw(25) << left << "\tClothing:"
              << setw(3) << right << "$ ";
        cin >> spentBudget.clothing;
    }

    cout << setw(25) << left << "\tMiscellaneous:"
          << setw(3) << right << "$ ";
    cin >> spentBudget.miscellaneous;

    while (spentBudget.clothing <= 0.0)
    {
        cout << setw(25) << left << "\tMiscellaneous:"
              << setw(3) << right << "$ ";
        cin >> spentBudget.clothing;
    }
}

/* **********************************************************
   Definition: calcTotal

    This function calculates the total amount spent during the
    month. The result is stored in the appropriate structure
    member.
   ********************************************************** */

void calcTotal(MonthlyBudget &spentBudget)
{
    spentBudget.total = spentBudget.housing      + spentBudget.utilities     +
                              spentBudget.householdExp + spentBudget.transport     +
                              spentBudget.food          + spentBudget.medical         +
                              spentBudget.insurance    + spentBudget.entertainment +
                              spentBudget.clothing        + spentBudget.miscellaneous;
}

/* **********************************************************
   Definition: calcBudget

    The ternary in this function determines whether the amount
    spent is greater, less, or equal to the budgeted amount.
    Based on the result, calculations are performed for each
    budget item. The result of the calculation, and whether
    the budget is over, under or equal to the budgeted amount
    is displayed.
   ********************************************************** */

void calcBudget(const double spentBudget, const double fixedBudget)
{
    const string overBudget         = "     over budget\n";
    const string underBudget    = "    under budget\n";
    const string balancedBudget = " balanced budget\n";

    cout << fixed << showpoint << setprecision(2);

    spentBudget > fixedBudget ? cout << (spentBudget - fixedBudget) << overBudget :
    spentBudget < fixedBudget ? cout << (fixedBudget - spentBudget) << underBudget :
                                         cout << (fixedBudget - spentBudget) << balancedBudget;
}

/* **********************************************************
   Definition: displayBudget

    This function displayes a detailed overview about each
    budget item.
   ********************************************************** */

void displayBudget(const MonthlyBudget spentBudget, const MonthlyBudget fixedBudget)
{
    cout << "\n\n\tMONTHLY BUDGET - EVALUATION\n\n\n";

    cout << "\tBUDGET ITEM"
          << setw(20) << right << "BUDGETED"
          << setw(20) << right << "SPENT"
          << setw(34) << right << "BUDGET STATUS";

    cout << "\n\t" << setw(97) << right << setfill('-') << "\n";

    cout << setfill(' ');
    cout << fixed << showpoint << setprecision(2);

    cout << setw(20) << left  << "\tHousing"
          << setw(5) << right  << "$ " << setw(7) << right << fixedBudget.housing
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.housing
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.housing, fixedBudget.housing);

    cout << setw(20) << left  << "\tUtilities"
          << setw(5)  << right << "$ " << setw(7) << right << fixedBudget.utilities
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.utilities
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.utilities, fixedBudget.utilities);

    cout << setw(20) << left  << "\tHousehold Expenses"
          << setw(5) << right  << "$ " << setw(7) << right << fixedBudget.householdExp
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.householdExp
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.householdExp, fixedBudget.householdExp);

    cout << setw(20) << left  << "\tTransport"
          << setw(5) << right  << "$ " << setw(7) << right << fixedBudget.transport
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.transport
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.transport, fixedBudget.transport);

    cout << setw(20) << left  << "\tFood"
          << setw(5) << right  << "$ " << setw(7) << right << fixedBudget.food
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.food
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.food, fixedBudget.food);

    cout << setw(20) << left  << "\tMedical"
          << setw(5) << right  << "$ " << setw(7) << right << fixedBudget.medical
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.medical
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.medical, fixedBudget.medical);

    cout << setw(20) << left  << "\tInsurance"
          << setw(5) << right  << "$ " << setw(7) << right << fixedBudget.insurance
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.insurance
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.insurance, fixedBudget.insurance);

    cout << setw(20) << left  << "\tEntertainment"
          << setw(5) << right  << "$ " << setw(7) << right << fixedBudget.entertainment
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.entertainment
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.entertainment, fixedBudget.entertainment);

    cout << setw(20) << left  << "\tClothing"
          << setw(5) << right  << "$ " << setw(7) << right << fixedBudget.clothing
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.clothing
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.clothing, fixedBudget.clothing);

    cout << setw(20) << left  << "\tMiscellaneous"
          << setw(5) << right  << "$ " << setw(7) << right << fixedBudget.miscellaneous
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.miscellaneous
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.miscellaneous, fixedBudget.miscellaneous);

    cout << "\t" << setw(97) << right << setfill('-') << "\n";
    cout << setfill(' ');

    cout << setw(20) << left  << "\tTotal"
          << setw(5) << right  << "$ " << setw(7) << right << fixedBudget.total
          << setw(16) << right << "$ " << setw(7) << right << spentBudget.total
          << setw(19) << right << "$ " << setw(7) << right;
    calcBudget(spentBudget.total, fixedBudget.total);
}

Example Output:




Tuesday, June 6, 2017

Programming Challenge 11.10 - Search Function For The Speaker's Bureau Program

 Include File: "UtilityCls.h"



/* Search Function For The Speaker's Bureau Program - This program is a
    modification of Programming Challenge 11.9. It allows the user to
    search for a speaker on a particular topic. It accepts a key word as
    an argument and then searches the array for a structure with that key
    word in the Speaking Topic field. All structures that match are displayed.
    If no structure matches, a message saying so is displayed. */

#include "UtilityCls.h"

struct SpeakerInfo
{
    string name;                /* The speaker's name                 */
    string phoneNum;            /* The speaker's telephone number */
    string speakingTopic;    /* The speaking topic                 */
    double fee;                   /* The speaker's fee                     */   
};

enum menuSelection
{
    GET_SPEAKER_INFO = 1,
    CHANGE_SPEAKER_INFO = 2,
    SEARCH_TOPICS = 3,
    DISPLAY_SPEAKER_INFO = 4,
    QUIT = 5
};

enum dataMode
{
    GET_INFO = 1,
    CHANGE_INFO = 2
};

void menu(SpeakerInfo [], const int);
int  menuItems();
void getSpeakerInfo(SpeakerInfo [], int, const int);
int  getSpeakerID(SpeakerInfo [], const int);
void searchTopic(SpeakerInfo [], const int);
void displaySpeakerInfo(SpeakerInfo [], const int);

int main()
{
    const int NUM_SPEAKERS = 10;

    SpeakerInfo speaker[NUM_SPEAKERS];

    menu(speaker, NUM_SPEAKERS);

   pauseSystem();
   return 0;
}

/* **********************************************************
    Definition: menuItems

    This function presents a menu-screen to the user from
    which he or she can select one of the available options.
    ********************************************************** */

int menuItems()
{
    int menuItem = 0;

    cout << "\n\t\tSPEAKER'S CORNER - SPEAKER INFORMATION\n\n"
          << "\tMenu Selection\n\n"
          << "\t1. Enter Speaker Info\n"
          << "\t2. Change Speaker Info\n"
          << "\t3. Search Speaker Topic\n"
          << "\t4. Display Speaker Info\n"
          << "\t5. Quit\n\n"
          << "\tYour Selection: ";
    cin >> menuItem;

    while (menuItem < GET_SPEAKER_INFO || menuItem > QUIT)
    {
        cout << "\n\tMenu item " << menuItem << " does not exist.\n\n"
              << "\tYour selection: ";
        cin >> menuItem;
    }

    return menuItem;
}

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

    This function represents the main-menu, from which all the
    other functions in this program are called.
   ********************************************************** */

void menu(SpeakerInfo speaker[], const int NUM_SPEAKERS)
{
    int selection = 0;
    int mode = 0;

    do
    {
        selection = menuItems();

        switch (selection)
        {
            case GET_SPEAKER_INFO:
            {
                clearScreen();
                cout << "\n\tSPEAKER'S CORNER - ENTER SPEAKER INFORMATION\n\n\n";

                mode = GET_INFO;
                getSpeakerInfo(speaker, mode, NUM_SPEAKERS);
            } break;

            case CHANGE_SPEAKER_INFO:
            {
                clearScreen();

                cout << "\n\tSPEAKER'S CORNER - CHANGE SPEAKER INFORMATION\n\n";
                mode = CHANGE_INFO;
                getSpeakerInfo(speaker, mode, NUM_SPEAKERS);
            } break;

            case SEARCH_TOPICS:
            {
                clearScreen();

                cout << "\n\tSPEAKER'S CORNER - TOPIC SEARCH\n\n";
                searchTopic(speaker, NUM_SPEAKERS);
            } break;

            case DISPLAY_SPEAKER_INFO:
            {
                clearScreen();

                cout << "\n\tSPEAKER'S CORNER - DISPLAY SPEAKER INFORMATION\n\n";
                displaySpeakerInfo(speaker, NUM_SPEAKERS);
            } break;

            case QUIT:
            {
                cout << "\n\tNow exiting 'Speaker's Corner' ...\n"
                          "\tHave a nice day!\n\n";
            } break;
        }
    } while (selection != QUIT);
}

/* **********************************************************
   Definition: getSpeakerID

    This function accepts an array of structure as argument.
    It displays a list of the speaker names. The user is asked
    to enter the speaker's ID, to determine whose info he or
    she wishes to change. The speaker's ID is returend.
   ********************************************************** */

int getSpeakerID(SpeakerInfo speaker[], const int NUM_SPEAKERS)
{
    int index = 0;
    int speakerID = 0;

    for (int index = 0; index < NUM_SPEAKERS; index++)
    {
        cout << "\tSpeaker # " << (index + 1) << "\t"
              << speaker[index].name << "\n";
    }

    cout << "\n\tEnter speaker ID: ";
    cin >> speakerID;

    cout << "\n\n";

    return speakerID - 1;
}

/* **********************************************************
   Definition: getSpeakerInfo

    This function asks the user to enter information about ten
    speakers. This information is stored in the appropriate
    members in the array of structures.
   ********************************************************** */

void getSpeakerInfo(SpeakerInfo speaker[], int mode, const int NUM_SPEAKERS)
{
    int index = 0;
    int numSpeakers = 0;

    if (mode == CHANGE_INFO)
    {
        index = getSpeakerID(speaker, NUM_SPEAKERS);
        numSpeakers = 1;
    }
    else
    {
        index = 0;
        numSpeakers = NUM_SPEAKERS;
    }

    do
    {
        cout << setw(23) << left << "\tSpeaker's Name: ";
        cin.ignore();
        getline(cin, speaker[index].name);

        while (speaker[index].name.empty())
        {
            cout << setw(23) << left << "\tSpeaker's Name: ";
            getline(cin, speaker[index].name);
        }

        cout << setw(22) << left << "\tSpeaker's Telephone #";
        getline(cin, speaker[index].phoneNum);

        while (speaker[index].phoneNum.empty())
        {
            cout << setw(22) << left << "\tSpeaker's Telephone #";
            getline(cin, speaker[index].phoneNum);
        }

        cout << "\tSpeaking Topic:\n\t";
        getline(cin, speaker[index].speakingTopic);

        while (speaker[index].speakingTopic.empty())
        {
            cout << setw(22) << left << "\tSpeaking Topic: ";
            getline(cin, speaker[index].speakingTopic);
        }

        cout << setw(23) << left << "\n\tRequired Fee $";
        cin >> speaker[index].fee;

        while (speaker[index].fee <= 0.0)
        {
            cout << setw(23) << left << "\tRequired Fee $";
            cin >> speaker[index].fee;
        }
        cout << "\n";

        index += 1;
    } while (index < numSpeakers);
}


/* **********************************************************
    Definition: searchTopic

    This function accpets an array of structures as argument.
    It asks the user to enter a key word to search for. If the
    key word is found, the matching speaker information is
    displayed. If there is no match, a message is displayed,
    and the function exits.
    ********************************************************** */

void searchTopic(SpeakerInfo speaker[], const int NUM_SPEAKERS)
{
    int     index = 0;
    int     speakerID = 0;
    string search = " ";
    bool     found = false;

    cout << "\n\tEnter a key word to search for: ";
    cin.ignore();
    getline(cin, search);

    for (index = 0; index < NUM_SPEAKERS; index++)
    {
        if (speaker[index].speakingTopic.find(search) != string::npos)
        {
            found = true;

            if (found)
            {
                cout << fixed << showpoint << setprecision(2);
                cout << setw(22) << left << "\n\tSpeaker's Name: "
                    << speaker[index].name
                    << setw(22) << left << "\n\tSpeaker's Telephone #"
                    << speaker[index].phoneNum
                    << setw(22) << left << "\n\tSpeaking Topic: "
                    << speaker[index].speakingTopic
                    << setw(22) << left << "\n\tRequired Fee: $"
                    << speaker[index].fee << "\n";
                cout << "\n\n";
            }
        }
    }

    if (!found)
    {
            cout << "\n\tNo topic matching this key word.\n\n";
    }

}

/* **********************************************************
   Definition: displaySpeakerInfo

    This function displays information about all speakers in
    the array of structures.
   ********************************************************** */

void displaySpeakerInfo(SpeakerInfo speaker[], const int NUM_SPEAKERS)
{

    for (int index = 0; index < NUM_SPEAKERS; index++)
    {
        cout << fixed << showpoint << setprecision(2);
        cout << setw(22) << left << "\n\tSpeaker's Name: "
              << speaker[index].name
              << setw(22) << left << "\n\tSpeaker's Telephone #"
              << speaker[index].phoneNum
              << setw(22) << left << "\n\tSpeaking Topic: "
              << speaker[index].speakingTopic
              << setw(22) << left << "\n\tRequired Fee: $"
              << speaker[index].fee << "\n";
    }   
    cout << "\n\n";
}

Example Output: 




Programming Challenge 11.9 - Speaker's Bureau

Include File: UtilityCls.h


/* Speaker's Bureau - This program keeps track of a speaker's bureau. The
    program uses a structure to store the following data about a speaker:

        * Name
        * Telephone Number
        * Speaking Topic
        * Fee Required

    The program uses an array of at least 10 structures. It lets the user
    enter data into the array, change the contents of any element, and
    display all the data stored in the array. The program has a menu-driven
    user interface.

    Input Validation: When the data for a new speaker is entered, the program
    ensures that the user has entered data for all the fields. No negative
    amounts for a speaker's fee are accepted. */

#include "UtilityCls.h"

struct SpeakerInfo
{
    string name;                /* The speaker's name                 */
    string phoneNum;            /* The speaker's telephone number */
    string speakingTopic;    /* The speaking topic                 */
    double fee;                   /* The speaker's fee                     */   
};

enum menuSelection
{
    GET_SPEAKER_INFO = 1,
    CHANGE_SPEAKER_INFO = 2,
    DISPLAY_SPEAKER_INFO = 3,
    QUIT = 4
};

enum dataMode
{
    GET_INFO = 1,
    CHANGE_INFO = 2
};

void menu(SpeakerInfo [], const int);
int  menuItems();
void getSpeakerInfo(SpeakerInfo [], int, const int);
int  getSpeakerID(SpeakerInfo [], const int);
void displaySpeakerInfo(const SpeakerInfo [], const int);

int main()
{
    const int NUM_SPEAKERS = 10;

    SpeakerInfo speaker[NUM_SPEAKERS];

    menu(speaker, NUM_SPEAKERS);

   pauseSystem();
   return 0;
}

/* **********************************************************
    Definition: menuItems

    This function presents a menu-screen to the user from
    which he or she can select one of the available options.
    ********************************************************** */

int menuItems()
{
    int menuItem = 0;

    cout << "\n\t\tSPEAKER'S CORNER - SPEAKER INFORMATION\n\n"
          << "\tMenu Selection\n\n"
          << "\t1. Enter Speaker Info\n"
          << "\t2. Change Speaker Info\n"
          << "\t3. Display Speaker Info\n"
          << "\t4. Quit\n\n"
          << "\tYour Selection: ";
    cin >> menuItem;

    while (menuItem < GET_SPEAKER_INFO || menuItem > QUIT)
    {
        cout << "\n\tMenu item " << menuItem << " does not exist.\n\n"
              << "\tYour selection: ";
        cin >> menuItem;
    }

    return menuItem;
}

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

    This function represents the main-menu, from which all the
    other functions in this program are called.
   ********************************************************** */

void menu(SpeakerInfo speaker[], const int NUM_SPEAKERS)
{
    int selection = 0;
    int mode = 0;

    do
    {
        selection = menuItems();

        switch (selection)
        {
            case GET_SPEAKER_INFO:
            {
                clearScreen();
                cout << "\n\tSPEAKER'S CORNER - ENTER SPEAKER INFORMATION\n\n\n";

                mode = GET_INFO;
                getSpeakerInfo(speaker, mode, NUM_SPEAKERS);
            } break;

            case CHANGE_SPEAKER_INFO:
            {
                clearScreen();

                cout << "\n\tSPEAKER'S CORNER - CHANGE SPEAKER INFORMATION\n\n";
                mode = CHANGE_INFO;
                getSpeakerInfo(speaker, mode, NUM_SPEAKERS);
            } break;

            case DISPLAY_SPEAKER_INFO:
            {
                clearScreen();

                cout << "\n\tSPEAKER'S CORNER - DISPLAY SPEAKER INFORMATION\n\n";
                displaySpeakerInfo(speaker, NUM_SPEAKERS);
            } break;

            case QUIT:
            {
                cout << "\n\tNow exiting 'Speaker's Corner' ...\n"
                          "\tHave a nice day!\n\n";
            } break;
        }
    } while (selection != QUIT);
}

/* **********************************************************
   Definition: getSpeakerID

    This function accepts an array of structure as argument.
    It displays a list of the speaker names. The user is asked
    to enter the speaker's ID, to determine whose info he or
    she wishes to change. The speaker's ID is returend.
   ********************************************************** */

int getSpeakerID(SpeakerInfo speaker[], const int NUM_SPEAKERS)
{
    int index = 0;
    int speakerID = 0;

    for (int index = 0; index < NUM_SPEAKERS; index++)
    {
        cout << "\tSpeaker # " << (index + 1) << "\t"
              << speaker[index].name << "\n";
    }

    cout << "\n\tEnter speaker ID: ";
    cin >> speakerID;

    cout << "\n\n";

    return speakerID - 1;
}

/* **********************************************************
   Definition: getSpeakerInfo

    This function asks the user to enter information about ten
    speakers. This information is stored in the appropriate
    members in the array of structures.
   ********************************************************** */

void getSpeakerInfo(SpeakerInfo speaker[], int mode, const int NUM_SPEAKERS)
{
    int index = 0;
    int numSpeakers = 0;

    if (mode == CHANGE_INFO)
    {
        index = getSpeakerID(speaker, NUM_SPEAKERS);
        numSpeakers = 1;
    }
    else
    {
        index = 0;
        numSpeakers = NUM_SPEAKERS;
    }

    do
    {
        cout << setw(23) << left << "\tSpeaker's Name: ";
        cin.ignore();
        getline(cin, speaker[index].name);

        while (speaker[index].name.empty())
        {
            cout << setw(23) << left << "\tSpeaker's Name: ";
            getline(cin, speaker[index].name);
        }

        cout << setw(22) << left << "\tSpeaker's Telephone #";
        getline(cin, speaker[index].phoneNum);

        while (speaker[index].phoneNum.empty())
        {
            cout << setw(22) << left << "\tSpeaker's Telephone #";
            getline(cin, speaker[index].phoneNum);
        }

        cout << "\tSpeaking Topic:\n\t";
        getline(cin, speaker[index].speakingTopic);

        while (speaker[index].speakingTopic.empty())
        {
            cout << setw(22) << left << "\tSpeaking Topic: ";
            getline(cin, speaker[index].speakingTopic);
        }

        cout << setw(23) << left << "\n\tRequired Fee $";
        cin >> speaker[index].fee;

        while (speaker[index].fee <= 0.0)
        {
            cout << setw(23) << left << "\tRequired Fee $";
            cin >> speaker[index].fee;
        }
        cout << "\n";

        index += 1;
    } while (index < numSpeakers);
}

/* **********************************************************
   Definition: displaySpeakerInfo

    This function displays information about all speakers in
    the array of structures.
   ********************************************************** */

void displaySpeakerInfo(const SpeakerInfo speaker[], const int NUM_SPEAKERS)
{
    for (int index = 0; index < NUM_SPEAKERS; index++)
    {
        cout << fixed << showpoint << setprecision(2);
        cout << setw(22) << left << "\n\tSpeaker's Name: "
              << speaker[index].name
              << setw(22) << left << "\n\tSpeaker's Telephone #"
              << speaker[index].phoneNum
              << setw(22) << left << "\n\tSpeaking Topic: "
              << speaker[index].speakingTopic
              << setw(22) << left << "\n\tRequired Fee: $"
              << speaker[index].fee << "\n";
    }
    cout << "\n\n";
}

Example Output:








Sunday, June 4, 2017

Programming Challenge 11.8 - Search Function For Customer Accounts

Include File:   UtilityCls.h
Example File: nameDB.txt


/* Search Function For Customer Accounts - This program is a modification
    of Programming Challenge 11.7. It adds a function that allows the user
    to search the structure array for a particular customer's account. It
    accepts part of the customer's name as an argument and then searches
    for an account with a name that matches it. All accounts that match are
    displayed. If no account matches, a message saying so is displayed. */

#include "UtilityCls.h"

struct AccountData
{
    int    accNumber;                /* The account number for new accounts             */   
    string name;                    /* The account holder's name                         */
    string address;                /* The account holder's address                     */
    string city;                    /* The city the account holder lives in         */
    string state;                    /* The state the account holder lives in         */
    string zipCode;                /* The states ZIP-code                                 */
    string telephoneNumber;        /* The account holder's telephone number         */
    double accountBalance;        /* The account balance                                 */
    string dateLastPayment;        /* The date of his or her last payment             */
};

enum menuSelection
{
    ENTER_DATA = 1,
    CHANGE_DATA = 2,
    VIEW_DATA = 3,
    QUIT = 4
};

enum dataMode
{
    GET_ACC_DATA = 1,
    CHANGE_ACC_DATA = 2
};

void menu(AccountData [], const int);
void getAccData(AccountData [], int, const int);
int  getAccID(AccountData [], const int);
bool validateInput(AccountData [], int, const int);
bool findData(AccountData[], int);
void displayData(AccountData [], const int);

int main()
{
    const int ACCOUNTS = 10;

    AccountData accData[ACCOUNTS];

    menu(accData, ACCOUNTS);

    pauseSystem();
    return 0;
}

/* **********************************************************
    Definition: menuItems

    This function presents a menu-screen to the user from
    which he or she can select one of the available options.
    ********************************************************** */

int menuItems()
{
    int menuItem = 0;

    cout << "\n\t\tASHIKAGA BANK - ACCOUNT MANAGER\n\n"
          << "\tMenu Selection\n\n"
          << "\t1. Enter Account Data\n"
          << "\t2. Change Account Data\n"
          << "\t3. View Account Data\n"
          << "\t4. Quit\n\n"
          << "\tYour Selection: ";
    cin >> menuItem;

    while (menuItem < ENTER_DATA || menuItem > QUIT)
    {
        cout << "\n\tMenu item " << menuItem << " does not exist.\n\n"
              << "\tYour selection: ";
        cin >> menuItem;
    }

    return menuItem;
}

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

    This function represents the main-menu, from which all the
    other functions in this program are called.
   ********************************************************** */

void menu(AccountData accHolder[], const int ACCOUNTS)
{
    int selection = 0;
    int mode = 0;

    do
    {
        selection = menuItems();

        switch (selection)
        {
            case ENTER_DATA:
            {
                clearScreen();

                cout << "\n\tASHIKAGA BANK - CUSTOMER ACCOUNT DATA SYSTEM\n\n";           
                mode = GET_ACC_DATA;
                getAccData(accHolder, mode, ACCOUNTS);
            } break;

            case CHANGE_DATA:
            {
                clearScreen();

                cout << "\n\tASHIKAGA BANK - CHANGE CUSTOMER ACCOUNT DATA\n\n";
                mode = CHANGE_ACC_DATA;
                getAccData(accHolder, mode, ACCOUNTS);
            } break;

            case VIEW_DATA:
            {
                clearScreen();

                cout << "\n\tASHIKAGA BANK - DISPLAY ACCOUNT INFORMATION\n\n";
                displayData(accHolder, ACCOUNTS);
            } break;

            case QUIT:
            {
                cout << "\n\tASHIKAGA BANK - CUSTOMER ACCOUNT DATA SYSTEM LOGOUT\n\t"
                      << "Remember Policy: Customer First!\n\n";
            } break;
        }
    } while (selection != QUIT);
}

/* **********************************************************
    Definition: getAccData

    This function accepts an array of structures as argument.
    The mode passed to the function determines what the user
    is asked for to input:
   
        * Account data (this includes entering an account-ID.)
        * Change data for an existing account (this excludes
          the account-ID member).

    In this way the function fulfills double-duty. It allows
    both entering a new set of data, as well as to change data
    for a specific account.
    ********************************************************** */

void getAccData(AccountData accHolder[], int mode, const int ACCOUNTS)
{
    int index = 0;
    int accNum = 0;
    int numAcc = ACCOUNTS;
    bool found = false;
    bool valid = false;

    if (mode == CHANGE_ACC_DATA)
    {
        accNum = getAccID(accHolder, ACCOUNTS);

        index = accNum;       
        numAcc = 1;               
    }

    do
    {
        /* This if-statement is only executed when the user has selected
           the option to enter data from the menu. */
        if (mode == GET_ACC_DATA)
        {
            cout << setw(29) << left << "\n\tEnter New Account ID: ";
            cin >> accHolder[index].accNumber;

            valid = validateInput(accHolder, index, ACCOUNTS);

            while (found = findData(accHolder, index))
            {
                cout << setw(29) << left << "\n\tEnter New Account ID: ";
                cin >> accHolder[index].accNumber;
            }
        }

        cout << setw(30) << left << "\n\tEnter Name: ";
        cin.ignore();
        getline(cin, accHolder[index].name);
       
        while (accHolder[index].name.empty() ||
                accHolder[index].name[index] == ' ')
        {
            cout << setw(28) << left << "\tEnter Name:";
            getline(cin, accHolder[index].name);
        }

        cout << setw(29) << left << "\tEnter Address:";
        getline(cin, accHolder[index].address);

        while (accHolder[index].address.empty())
        {
            cout << setw(29) << left << "\tEnter Address:";
            getline(cin, accHolder[index].address);
        }

        cout << setw(29) << left << "\tEnter Name of City:";
        getline(cin, accHolder[index].city);

        while (accHolder[index].city.empty() ||
                   accHolder[index].city[index] == ' ')
        {
            cout << setw(29) << left << "\tEnter Name of City: ";
            getline(cin, accHolder[index].city);
        }

        cout << setw(29) << left << "\tEnter Name of State:";
        getline(cin, accHolder[index].state);

        while (accHolder[index].state.empty())
        {
            cout << setw(29) << left << "\tEnter Name of State:";
            getline(cin, accHolder[index].state);
        }

        cout << setw(29) << left << "\tEnter ZIP-Code:";
        getline(cin, accHolder[index].zipCode);

        while (accHolder[index].zipCode.empty()  ||
                 accHolder[index].zipCode.length() != 8)
        {
            cout << setw(29) << left << "\tEnter ZIP-Code";
            getline(cin, accHolder[index].zipCode);
        }

        cout << setw(29) << left << "\tEnter Telephone Number:";
        getline(cin, accHolder[index].telephoneNumber);

        while (accHolder[index].telephoneNumber.empty())
        {
            cout << setw(29) << left << "\tEnter Telephone Number: ";
            getline(cin, accHolder[index].telephoneNumber);
        }

        cout << setw(29) << left << "\tEnter Account Balance: ";
        cin >> accHolder[index].accountBalance;

        while (accHolder[index].accountBalance <= 0)
        {
            cout << setw(29) << left << "\tEnter Account Balance: ";
            cin >> accHolder[index].accountBalance;
        }

        cout << setw(29) << left << "\tEnter Date of Last Payment: ";
        cin.ignore();
        getline(cin, accHolder[index].dateLastPayment);

       
        while (accHolder[index].dateLastPayment.empty() ||
                accHolder[index].dateLastPayment.length() < 10)
        {
            cout << setw(29) << left << "\tEnter Date of Last Payment: ";
            getline(cin, accHolder[index].dateLastPayment);
        }

        index += 1;
    } while (index < numAcc);
}

/* **********************************************************
   Definition: findData

    This function accepts an array of structures, as well as
    an array index as arguments. It determines, whether an
    account ID already exists in the database. The result is
    returned.
   ********************************************************** */

bool findData(AccountData accHolder[], int accID)
{
    bool found = false;

    for (int index = 0; index < accID; index++)
    {
        if (accHolder[index].accNumber == accHolder[accID].accNumber)
        {
            cout << "\n\tAccount-ID taken.\n";
            found = true;
        }
    }

    return found;
}

/* **********************************************************
    Definition: validateInput

    This function accepts an array of structures, as well as
    an array index as arguments. It verifies, that the account
    number is not lower than or equal to 0.
    ********************************************************** */

bool validateInput(AccountData accHolder[], int accID, const int ACCOUNTS)
{
    bool valid = false;

    while (accHolder[accID].accNumber <= 0)
    {
        cout << setw(29) << left << "\n\tEnter New Account ID: ";
        cin >> accHolder[accID].accNumber;
    }

    return valid;
}

/* **********************************************************
    Definition: getAccID

    This function accpets an array of structures as argument.
    It asks the user to enter a full or partial name. If the
    name or names are found, they are displayed, and the user
    is asked to enter the ID of the account he or she wishes
    to view or change data for. If no match is found, the user
    is informed by a message.
    ********************************************************** */

int getAccID(AccountData accHolder[], const int ACCOUNTS)
{
    int     index = 0;
    int     accID = 0;
    string searchName = " ";
    bool     found = false;

    cout << "\n\tEnter a name (partial or full) to search for: ";
    cin.ignore();
    getline(cin, searchName);

    for (index = 0; index < ACCOUNTS; index++)
    {
        if (accHolder[index].name.find(searchName) != string::npos)
        {       
            cout << "\n\tAccount Name: " << (index + 1)
                  << " " << accHolder[index].name << "\n";
            found = true;
        }
    }

    if (found == true)
    {
        cout << "\n\tEnter Account ID: ";
        cin >> accID;

        accID -= 1;        /* To keep input in sync with array indices */
    }
    else
    {
        cout << "\n\tThis name was not found in database!\n";
        accID = -1;
    }
   
    return accID;
}

/* **********************************************************
   definition: displayData

    This function accepts an array of structures as argument.
    It displays information about a specific customer, stored
    in the array.
   ********************************************************** */

void displayData(AccountData accHolder[], const int ACCOUNTS)
{
    int accID = 0;
    int index = 0;

    /* This is going to hold the name-search */
    accID = getAccID(accHolder, ACCOUNTS);
   
    if (accID != -1)
    {
        cout << fixed << showpoint << setprecision(2);

        cout << setw(24) << left << "\n\tAccount ID #"
                << accHolder[accID].accNumber
              << setw(24) << left << "\n\tAccount Holder: "
              << accHolder[accID].name
              << setw(24) << left << "\n\tAddress: "
              << accHolder[accID].address
              << setw(24) << left << "\n\tCity: "
              << accHolder[accID].city
              << setw(24) << left << "\n\tState: "
              << accHolder[accID].state
              << setw(24) << left << "\n\tZIP-Code: "
              << accHolder[accID].zipCode
              << setw(24) << left << "\n\tTelephone #"
              << accHolder[accID].telephoneNumber
              << setw(24) << left << "\n\tAccount Balance JPY: "
              << accHolder[accID].accountBalance
              << setw(24) << left << "\n\tDate of Last Payment: "
              << accHolder[accID].dateLastPayment << "\n\n";
    }
}

Example Output: