/* Backward String - This program contains a funtion that accepts a
pointer to a C-string as an argument. It displays the contents
backward. For instance, if the string argument is "Gravity", the
function displays "ytivarG". This function is demonstrated by
asking the user to input a string that is passed to the function. */
#include "Utility.h"
/* Reverses a string entered by the user and displays it */
void reverseString(char *);
int main()
{
const int NUM_CHARS = 51;
/* Array to hold the word(s) */
char *word = new char[NUM_CHARS]();
char again = ' ';
do
{
cout << "\n\tBACKWARD STRING - GNIRTS DRAWKCAB\n\n"
<< "\tEnter a word of up to " << (NUM_CHARS - 1)
<< " characters and I will reverse it: ";
cin.getline(word, NUM_CHARS);
reverseString(word);
/* Ask the user if he or she wishes to enter another word */
cout << "\n\tDo you wish to enter another word? ";
cin.get(again);
/* Input validation */
while (toupper(again) != 'Y' && toupper(again) != 'N')
{
cout << "\n\tEnter 'Y' or 'N': ";
cin.ignore();
cin.get(again);
}
if (toupper(again) == 'Y')
{
cin.getline(word, NUM_CHARS);
}
else
{
cout << "\n\t!yeB dooG\n\n";
}
} while (toupper(again) == 'Y');
/* Frees the memory */
delete[] word;
word = nullptr;
pauseSystem();
return 0;
}
/* **********************************************************
Definition: reverseString
This function accepts a pointer to a C-string as argument.
After the string is reversed, using the swap function, the
word is displayed backwards.
********************************************************** */
void reverseString(char *revPtr)
{
int forward = 0,
backward = strlen(revPtr);
while (forward < backward)
{
--backward;
swap(*(revPtr + forward), *(revPtr + backward));
forward++;
}
cout << "\tThis is your word backwards: " << revPtr << "\n";
}
Thursday, April 6, 2017
Programming Challenge 10.2 - Backward String
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment