Friday, April 21, 2017

Programming Challenge 10.7 - Name Arranger

/* Name Arranger - This program asks for the user's first, middle and
    last names. The names should be stored in three different character
    arrays. The program then stores, in a fourth array, the name arranged
    in the following manner:
   
        * The last name followed by a comma and a space, followed by the
          first name and a space, followed by the middle name.
         
    For example, if the user enters "Carol Lynn Smith", it stores "Smith,
    Carol Lynn" in the fourth array. The contents of the fourth array is
    displayed on the screen. */

#include "Utility.h"

/* Arranges the name in the order last, first, and middle name,
    stores it in an array, returns a pointer to the array */
char *nameArranger(const char *, const char *, const char *);

int main()
{
    const int NAME_SIZE = 30;

    char         firstName[NAME_SIZE],
                 middleName[NAME_SIZE],
                 lastName[NAME_SIZE];

    char        *fullName = " ";

    cout << "\n\tName Arranger\n\n"
          << "\tEnter your first name: ";
    cin.getline(firstName, NAME_SIZE);

    cout << "\n\tEnter your middle name: ";
    cin.getline(middleName, NAME_SIZE);

    cout << "\n\tEnter your last name: ";
    cin.getline(lastName, NAME_SIZE);

    cout << "\n\tYour full name, sorted in order of last-,\n\t"
              "first-, and middle name: "
          << (fullName = nameArranger(firstName, middleName, lastName))
          << "\n\n";

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: nameArranger

    This function accepts three pointers to C-string objects
    as argument. The names are concatenated and stored in a
    char array. A pointer to this array is returned.
   ********************************************************** */

char *nameArranger(const char *firstName, const char *middleName,
                         const char *lastName)
{
    const int MAX_CHARS = 50;
   
    char *fullName = new char[MAX_CHARS]();

    strcat_s(fullName, MAX_CHARS, lastName);
    strcat_s(fullName, MAX_CHARS, ", ");
    strcat_s(fullName, MAX_CHARS, firstName);
    strcat_s(fullName, MAX_CHARS, " ");
    strcat_s(fullName, MAX_CHARS, middleName);

    return fullName;
}

Example Output:



No comments:

Post a Comment