Thursday, April 6, 2017

Programming Challenge 10.1 - String Length

/* String Length - This program contains a function that returns an
   integer and accepts a pointer to a C-string as an argument. The
   function counts the number of characters in the string and returns
   that number. The user is asked to input a string, which is passed
   to the function, and then displays the function's return value. */

#include "Utility.h"

/* Counts characters in a C-string, returns the character count. */
int countChars(const char *);

int main()
{
   const int NUM_CHARS = 100;

   /* Char array to hold a sentence */
   char *sentence = new char[NUM_CHARS]();

   char again = ' ';
   int  letterCount = 0;

   do
   {
      /* Get a sentence from the user */
      cout << "\n\t\t\tCHARACTER COUNTER\n\n"
           << "\tEnter a sentence of up to " << (NUM_CHARS - 1)
           << " characters: ";
      cin.getline(sentence, NUM_CHARS);

      /* Display the number of characters in the string */
      cout << "\n\tThis sentence contains "
           << (letterCount = countChars(sentence))
           << " characters.\n";

      /* Ask if the user wishes to enter another sentence */
      cout << "\n\tDo you wish to enter another sentence ('Y' or 'N')? ";
      cin.get(again);

      /* Input validation */
      while (toupper(again) != 'Y' && toupper(again) != 'N')
      {
         cout << "\n\tEnter 'Y' or 'N' to enter another sentence: ";
         cin.ignore();
         cin.get(again);
      }

      /* If again is 'y', another sentence may be entered. */
      if (toupper(again) == 'Y')
      {
         cin.getline(sentence, NUM_CHARS);
      }
      else
      {
         cout << "\n\tGood bye!\n\n";
      }

   } while (toupper(again) == 'Y');

   /* Frees the memory */
   delete[] sentence;
   sentence = nullptr;

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: countChars

   This function contains chrPtr, pointing to the C-string
   containing a sentence the user entered. It counts the
   characters and returns this number as an integer value.
   ********************************************************** */

int countChars(const char *chrPtr)
{
   int numChars = 0;

   while (*chrPtr != '\0')
   {
       numChars++;
      *chrPtr++;
   }

   return numChars;
}

Example Output:



No comments:

Post a Comment