Friday, April 28, 2017

Programming Challenge 10.13 - Date Printer

/* Date Printer - This program reads a string from the user containing a
   date in the form mm/dd/yyyy. It prints the date in the form March 12,
    2014. */

#include "Utility.h"

/* Performs various checks to confirm validity of input,
    returns the result */
bool checkDate(string);

/* Determines the correct month name,
   returns the month name */
string months(int);

/* Inserts month, day and year into the date string,
   displays the date */
void printDate(string, int, int);

int main()
{
    int    month = 0,
             day = 0,
            year = 0;
    string date = " ";

    cout << "\n\tDATE PRINTER\n\n"
          << "\tEnter a date in the format 'mm/dd/yyyy' and I will\n"
          << "\tconvert and display it. For example, after entering\n"
          << "\t'01/12/2017', the output will be 'January 12, 2017.'\n\n"
          << "\tPlease enter a date: ";
    getline(cin, date);

    while (checkDate(date) == false)
    {
        if (checkDate(date) == false)
        {
            cout << "\n\tThe date entered is invalid.\n"
                  << "\tPlease enter a date: ";
            getline(cin, date);
        }
    }

    month = stoi(date.substr(0));
    day = stoi(date.substr(3));
    year = stoi(date.substr(6));

    date = months(month);
             printDate(date, day, year);

    pauseSystem();
    return 0;
}

/* **********************************************************
   Definition: checkDate

    This function performs the following checks on the string

        * Correct length of the date string (This is the only
          condition that immediately returns the result in case
          the validity check fails)
        * Existence of delimiting characters '/'
        * Correctness of month, day, year input
        * Determins whether the year is a leap year. Based on
          the result, the month and day input is validated once
          more.

    The result is returned.
   ********************************************************** */

bool checkDate(string date)
{

    bool validDate = true;
    bool isLeapYear = false;
    int  month = 0,
          day = 0,
          year = 0;
    char delimiter = '/';

    if (date.length() < 10)
    {
        return validDate = false;
    }

    if (date.at(2) != delimiter || date.at(5) != delimiter)
    {
        validDate = false;
    }

    month = stoi(date.substr(0));

    if (month < 1 || month > 12)
    {
        validDate = false;
    }
   
    day = stoi(date.substr(3));

    if (day < 1 || day > 31)
    {
        validDate = false;
    }

    year = stoi(date.substr(6));

    if (year < 1 || year > 2100)
    {
        validDate = false;
    }

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

    if (isLeapYear && month == 2 && day > 29)
    {
        validDate = false;
    }

    if (isLeapYear == false && month == 2 && day > 28)
    {
        validDate = false;
    }

    return validDate;
}

/* **********************************************************
   Definition: months

    This function determines the name of a month, based on the
    integer value passed to it. The name is returned.
   ********************************************************** */

string months(const int month)
{
    const string monthNames[12] = { "January", "February", "March",
                                              "April", "May", "June", "July",
                                              "August", "September", "October",
                                              "November", "December" };

    return monthNames[month-1];
}

/* **********************************************************
   Definition: printDate

    This function accepts a string and two int values as
    arguments. It inserts day and year into the date string,
    and displays the date.
   ********************************************************** */

void printDate(string date, int day, int year)
{
    date.insert(date.length(), " " + to_string(day) + ", " + to_string(year));

    cout << "\n\tYour date is: " << date << endl;
}

Example Output:




Thursday, April 27, 2017

Programming Challenge 10.12 - Password Verifier

/* Password Verifier - Imagine we are developing a software package that
    requires users to enter their own passwords. Our software requires that
    user's passwords meet the following criteria:
  
        * The password should be at least six characters long
        * The password should contain at least one uppercase
          and at least one lowercase letter
        * The password should have at least one digit

    This program asks for a password and then verifies that it meets the
    stated criteria. If it doesn't, the program displays a message telling
    the user why. */

#include "Utility.h"

/* Determines the length of password,
    returns the result */
bool checkLength(string);

/* Determines whether the password contains uppercase characters,
    returns the result */
bool containsUpper(string);

/* Determines whether the password contains lowercase characters,
    returns the result */
bool containsLower(string);

/* Determines whether the password contains digits,
    returns the result */
bool containsDigit(string);

int main()
{  
    int    numTries = 5;
    string passphrase = "moRioka9713";
    string password = " ";

    cout << "\n\tKaibun Game - Login\n"
          << "\t-------------------\n";

    do
    {
        cout << "\n\tPlease enter your password: ";
        getline(cin, password);

        if (password != passphrase)
        {
            if (checkLength(password) == false)
            {
                cout << "\n\tPassword length mismatch.\n";
            }

            if (containsUpper(password) == false)
            {
                cout << "\tPassword does not contain uppercase characters.\n";
            }

            if (containsLower(password) == false)
            {
                cout << "\tPassword does not contain lowercase characters.\n";
            }

            if (containsDigit(password) == false)
            {
                cout << "\tPassword does not contain digits.\n";
            }

            cout << "\n\tYou have " << (numTries -= 1) << " tries left\n";

            if (numTries == 0)
            {
                cout << "\n\tYour password could not be verified.\n"
                      << "\tNow closing this program ...";
            }
        }

        else if (password == passphrase)
        {
            cout << "\n\tYou have been verified successfully.\n";
        }
    } while (numTries > 0 && password != passphrase);

    pauseSystem();
    return 0;
}

/* **********************************************************
    Definition: checkLength

    This function verifies that the password is at least six
    characters long. The result is returned.
    ********************************************************** */

bool checkLength(string password)
{
    bool length = false;

    password.length() >= 6 ? length = true : length = false;

    return length;
}

/* **********************************************************
    Definition: containsUpper

    This function verifies that the password contains at least
    one uppercase character. The result is returned.
    ********************************************************** */

bool containsUpper(string password)
{
    bool isUpper = false;

    for (size_t i = 0; i < password.length(); i++)
    {
        if (isupper(password[i]))
        {
            isUpper = true;
        }
    }

    return isUpper;
}

/* **********************************************************
    Definition: containsLower

    This function verifies that the password contains at least
    one lowercase character. The result is returned.
    ********************************************************** */

bool containsLower(string password)
{
    bool isLower = false;

    for (size_t i = 0; i < password.length(); i++)
    {
        if (islower(password[i]))
        {
            isLower = true;
        }
    }

    return isLower;
}

/* **********************************************************
    Definition: containsDigit

    This function determines whether the password contains any
    digits. The result is returned.
    ********************************************************** */

bool containsDigit(string password)
{
    bool isDigit = false;

    for (size_t i = 0; i < password.length(); i++)
    {
        if (isdigit(password[i]))
        {
            isDigit = true;
        }
    }

    return isDigit;
}

Example Output:




Tuesday, April 25, 2017

Programming Challenge 10.11 - Case Manipulator

/* Case Manipulator - This program contains three functions, upper, lower,
    and reverse.

    * The upper function accepts a pointer to a C-string as an argument.
      It steps through each character in the string, converting it to
      uppercase.

    * The lower function, too, accepts a pointer to a C-string as an
      argument. It steps through each character in the string, converting
      it to lowercase.

    * Like upper and lower, reverse accepts a pointer to a C-string. As it
      steps through the string, it tests each character to determine
      whether it is upper- or lowercase. If a character is uppercase, it
      is converted to lowercase. Likewise, if a character is lowercase,
      it is converted to uppercase.

    The functions are tested by asking for a string in function main, then
    passing it to them in the order: reverse, lower, and upper.    */

#include "Utility.h"

/* Determines character casing, changing upper- to lowercase letters
   and vice versa */
void reverse(char *);

/* Converts all characters from upper- to lowercase */
void lowercase(char *);

/* Converts all characters from lower- to uppercase */
void uppercase(char *);

int main()
{
    const int MAX_CHARS = 501;
    char         sentence[MAX_CHARS];

    cout << "\n\tCASE MANIPULATOR\n\n\t"
          << "Enter a sentence, " << (MAX_CHARS - 1)
          << " characters in length, and I will\n\t"
          << "first reverse all upper and lowercase characters, then\n\t"
          << "I will change all characters to lowercase, and lastly I\n\t"
          << "will change all characters to uppercase.\n\n";

    cout << "\n\tPlease enter your sentence:\n\t";
    cin.getline(sentence, MAX_CHARS);

    cout << "\n\n\tCHARACTER CASE REVERSAL\n";
    reverse(sentence);

    cout << "\n\tAll character cases have been reversed:\n"
          << "\t" << sentence << "\n\n";

    cout << "\n\tCHARACTERS TO LOWERCASE:\n";
    lowercase(sentence);

    cout << "\n\tAll uppercase characters have been changed "
          << "to lowercase:\n"
          << "\t" << sentence << "\n\n";
   
    cout << "\n\tCHARACTERS TO UPPERCASE:\n";
    uppercase(sentence);

    cout << "\n\tAll lowercase characters have been changed "
          << "to uppercase:\n"
          << "\t" << sentence << "\n\n";

    pauseSystem();
    return 0;
}

/* **********************************************************
   Definition: reverse

    This function accepts a pointer to a C-string as argument.
    It reverses all upercase characters to lowercase and vice
    versa.
   ********************************************************** */

void reverse(char *senPtr)
{
    for (size_t index = 0; senPtr[index] != '\0'; index++)
    {
        if (isupper(senPtr[index]))
        {
            senPtr[index] = tolower(senPtr[index]);
        }
       
        else if (islower(senPtr[index]))
        {
            senPtr[index] = toupper(senPtr[index]);
        }
    }
}

/* **********************************************************
    Definition: lowercase

    This function accepts a pointer to a C-string as argument.
    It converts all characters from upper- to lowercase.
    ********************************************************** */

void lowercase(char *senPtr)
{
    for (size_t index = 0; senPtr[index] != '\0'; index++)
    {
        if (isupper(senPtr[index]))
        {
            senPtr[index] = tolower(senPtr[index]);
        }
    }
}

/* **********************************************************
   Definition: uppercase

    This function accepts a pointer to a C-string as argument.
    It converts all characters from lower- to uppercase.
   ********************************************************** */

void uppercase(char *senPtr)
{
    for (size_t index = 0; senPtr[index] != '\0'; index++)
    {
        if (islower(senPtr[index]))
        {
            senPtr[index] = toupper(senPtr[index]);
        }
    }
}

Example Output:



Monday, April 24, 2017

Programming Challenge 10.10 - Replace Substring Function

/* Replace Substring Function - This program contains a function called
    replaceSubstring. It accepts three string objects as arguments. It
    searches string1 for all occurrences in string2. When it finds an
    occurrence of string2, it replaces it with string3. For example,
    suppose the three arguments have the following values:
  
        * string1:        "the dog jumped over the fence"
        * string2:        "the"
        * string3:        "that"

    With these three arguments, the function returns a string object
    with the value "that dog jumped over the fence." */

#include "Utility.h"

/* Asks the user if he or she wants to repeat the process,
    returns the decision */
char tryAgain();

/* Introduces the functionality of this program to the user */
void intro();

/* Decapitalizes the first character in a sentence */
void senDecapitalizer(string &, string &);

/* Capitalizes the first character at the beginning of each sentence */
void senCapitalizer(string &);

/* Searches for all occurrences of a word entered by the user in a
    sentence, replaces this word, returns a string object which
    contains the new sentence */
string replaceSubstring(const string, const string, const string);

int main()
{
    int     firstRun = 1;
    char     again = ' ';
    string sentence = " ";
    string searchWord = " ";
    string replaceWord = " ";
    string altered = " ";

    do
    {
        if (firstRun)
        {
            intro();
            firstRun = 0;
        }
        else
        {
            cout << "\n\n\tWORD REPLACER\n\n";
        }

        cout << "\n\tEnter a sentence: ";
        getline(cin, sentence);

        cout << "\n\tThis is your original sentence:\n\t"
              << sentence;

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

        senDecapitalizer(sentence, searchWord);

        cout << "\n\tEnter a word to replace the "
              << "\'" << searchWord << "\' with: ";
        getline(cin, replaceWord);

        altered = replaceSubstring(sentence, searchWord, replaceWord);

        senCapitalizer(altered);

        cout << "\n\tThis is your altered sentence:\n"
              << "\t" << altered << " ";

        again = tryAgain();

        if (again == 'N')
        {
            cout << "\n\tHave a nice day!\n\n";
        }

    } while (again == 'Y');

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: intro

    This function introduces the basic functionality of this
    program to the user.
   ********************************************************** */

void intro()
{
    cout << "\n\tWORD REPLACER\n\n"
          << "\tThis program first asks you to enter a sentence, then\n"
          << "\tyou are asked to enter a word to be searched for. If the\n"
          << "\tword exists, you are asked to enter a word or words the\n"
          << "\tsearch word should be replaced with. For example, if this\n"
          << "\tis the sentence you entered:\n\n"
          << "\t'The quick brown fox jumped over the lazy dog.'\n\n"
          << "\tIf you search for 'the,' (without quotes), and the word to\n"
          << "\treplace 'the' is 'that', your sentence will be changed to:\n\n"
          << "\t'That quick brown fox jumped over that lazy dog.'\n\n"
          << "\tNote that the input is case-insensitive. You can enter a\n"
          << "\tsentence containing lowercase characters only, or a mixture\n"
          << "\tof both lower and uppercase characters. The same applies to\n"
          << "\tthe word to search for. In other words you can enter:\n\n"
          << "\t'THE', 'tHe' or simply 'the' if you wish to.\n\n"
          << "\tYou can repeat this process by entering 'y' or 'Y', when\n"
          << "\tasked.\n\n";
}

/* **********************************************************
   Definition: tryAgain

    This function asks the user if he or she wishes to try
    again. This decision is returned.
   ********************************************************** */

char tryAgain()
{
    char again = ' ';

    cout << "\n\n\tDo you wish to try this again? ";
    cin >> again;
    cin.ignore();

    /* Input validation */
    while (toupper(again) != 'Y' && toupper(again) != 'N')
    {
        cout << "\n\tDo you wish to try this again? ";
        cin >> again;
        cin.ignore();
    }

    return toupper(again);
}

/* **********************************************************
   Definition: senCapitalizer

   This function accepts two string class objects. If one or
    the other contains uppercase characters, they are changed
    to lowercase.
   ********************************************************** */

void senDecapitalizer(string &sentence, string &searchWord)
{
      for (unsigned int i = 0; i < sentence.length(); i++)
    {
        if (isupper(sentence[i]))
        {
            sentence[i] = tolower(sentence[i]);
        }
    }
}

/* **********************************************************
   Definition: replaceSubstring

    This function accepts three string objects as argument. It
    searches the original sentence for a string entered by the
    user, and if it is found, replaces the word or words. The
    altered sentence is returned.
   ********************************************************** */

string replaceSubstring(const string sentence, const string searchWord,
                                const string replaceWord)
{
    string altered = sentence;  
    size_t findWord = altered.find(searchWord);

    while (findWord != string::npos)
    {
        altered.replace(findWord, searchWord.size(), replaceWord);
        findWord = altered.find(searchWord, findWord + replaceWord.length());
    }

    return altered;
}

/* **********************************************************
   Definition: senCapitalizer

   This function accepts a string class object as argument.
   It capitalizes the first letter in each sentence.
   ********************************************************** */

void senCapitalizer(string &sentence)
{
    unsigned int index = 0;
    bool         isDelim = false;

    for (index = 0; index < sentence.length(); index++)
    {
        if (sentence.at(index) == '.' || sentence.at(index) == '!' ||
            sentence.at(index) == '?')
        {
            isDelim = false;
        }

        if (isalpha(sentence.at(index)) && isDelim == false)
        {
            isDelim = true;
            sentence.at(index) = toupper(sentence.at(index));
        }
    }
}

Example Output:






Sunday, April 23, 2017

Programming Challenge 10.9 - Most Frequent Character

/* Most Frequent Character - This program contains a function that accepts
    a string object as its argument. The function returns the character that
    appears most frequently in the string. */

#include "Utility.h"

/* Finds the most frequently occuring character in the string,
    stores the frequency in a reference variable, returns the
    most frequently occuring character */
char mostFreq(string, unsigned int &);

int main()
{
    unsigned int frequency = 0;
    char             mostFreqChar = ' ';    
    string         sentence = " ";
  
    cout << "\n\tMost Frequent Character\n\n"
          << "\tEnter a sentence, and I will show you, what the most\n"
          << "\tfrequently occuring character is.\n\n"
          << "\tPlease enter your sentence: ";
    getline(cin, sentence);

    mostFreqChar = mostFreq(sentence, frequency);

    cout << "\n\tThe most frequent character is "
          << '\'' << mostFreqChar << '\'' << ", appearing "
          << frequency << " times in your sentence.";

   pauseSystem();
   return 0;
}

/* **********************************************************
    Definition: mostFreq

    This function accepts a string class object as argument.
    It determines the most frequently appearing character in
    the string and returns it. The frequency in which this
    character appears is stored in a reference variable.
   ********************************************************** */

char mostFreq(string sentence, unsigned int &frequency)
{
    unsigned int index = 0,
                     startScan = 0,
                     charCount = 0;
    char             mostFreqChar = ' ';

    for (startScan = index + 1; startScan < sentence.size(); startScan++)
    {
        charCount = 0;

        for (index = 0; index < sentence.size(); index++)
        {
            if (isalpha(sentence[index]) && isalpha(sentence[startScan]))
            {
                if (tolower(sentence[startScan]) == tolower(sentence[index]))
                {
                    charCount++;
                }

                if (charCount > frequency)
                {
                    frequency = charCount;
                    mostFreqChar = (tolower(sentence[index]));
                }
            }
        }
    }

    return mostFreqChar;
}

Example Output:





Saturday, April 22, 2017

Programming Challenge 10.8 - Sum Of Digits

/* Sum Of Digits - This program asks the user to enter a series of
    single digit numbers with nothing separating them. The input is
    read as a string object. The program displays the sum of all the
    single-digit numbers in the string. For example, if the user enters
    2514, the program displays 12, which is the sum of 2, 5, 1, and 4.
    It also displays the highest and lowest digits in the string. */

#include "Utility.h"

/* Calculates the sum-total of numbers in a string class object,
    returns this number */
int sumOfNumbers(string);

/* Finds the smallest number in a string class object, returns
    this number */
int findLowest(string);

/* Finds the highest number in a string class object, returns
    this number */
int findHighest(string);

/* Asks the user if he or she wants to repeat the process,
    returns the decision */
char tryAgain();

int main()
{
    int     total = 0,
             lowestNum = 0,
             highestNum = 0;
    char   again = ' ';
    string numbers = " ";
   
    do
    {
        cout << "\n\n\t\tSUM OF DIGITS\n\n"
              << "\tEnter a series of numbers without spaces in between\n"
              << "\tand I will calculate the sum of numbers for you.\n\n\t"
              << "Please enter your numbers: ";
        getline(cin, numbers);

        cout << "\n\n\tThe sum of your numbers is: "
              << (total = sumOfNumbers(numbers)) << "\n\n\t";

        cout << "This is the lowest number found: " << setw(2) << right
              << (lowestNum = findLowest(numbers)) << "\n\t";

        cout << "This is the highest number found: "
              << (highestNum = findHighest(numbers)) << "\n\n\t";

        again = tryAgain();

        if (again == 'N')
        {
            cout << "\n\tHave a nice day!\n\n";
        }

    } while (again == 'Y');

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: sumOfNumbers

    This function accepts a string class object as argument.
    It calculates the sum of numbers in the string. The sum-
    total is returned.
   ********************************************************** */

int sumOfNumbers(string numbers)
{
    int total = 0;

    for (unsigned int index = 0; index < numbers.size(); index++)
    {
        total += numbers[index] - '0';
    }

    return total;
}

/* **********************************************************
   Definition: findLowest

    This function accepts a string class object as argument.
    It determines the lowest number and returns it.
   ********************************************************** */

int findLowest(string numbers)
{
    int lowestNum = numbers[0] - '0';

    for (unsigned int index = 0; index < numbers.size(); index++)
    {
        if (lowestNum > numbers[index] - '0')
        {
            lowestNum = numbers[index] - '0';
        }
    }

    return lowestNum;
}

/* **********************************************************
   Definition: findHighest

    This function accepts a string class object as argument.
    It determines the highest number in a string and returns
    it.
   ********************************************************** */

int findHighest(string numbers)
{
    int highestNum = numbers[0] - '0';

    for (unsigned int index = 0; index < numbers.size(); index++)
    {
        if (highestNum < numbers[index] - '0')
        {
            highestNum = numbers[index] - '0';
        }
    }

    return highestNum;
}

/* **********************************************************
   Definition: tryAgain

    This function asks the user if he or she wishes to try
    again. This decision is returned.
   ********************************************************** */

char tryAgain()
{
    char again = ' ';

    cout << "Do you wish to try this again? ";
    cin >> again;
    cin.ignore();

    /* Input validation */
    while (toupper(again) != 'Y' && toupper(again) != 'N')
    {
        cout << "Do you wish to try this again? ";
        cin >> again;
        cin.ignore();
    }

    return toupper(again);
}

Example Output:




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: