Search This Blog

Monday, May 9, 2011

C++ Backward String Program


Backward String 

Write a function that accepts a C-string as an argument and displays its contents backwards. For instance, if the string argument is “Gravity” the function should display “ytivarG”. Demonstrate the function in a program that asks the user to input a string and then passes it to the function. 

Here is the output: (Click to enlarge)
Here is the code:
// Kim Pestana C++, Chapt. 11, Backward String
// Backward String
// Write a function that accepts a C-string as an argument and
// displays its contents backwards. For instance, if the string argument is “Gravity”
// the function should display “ytivarG”. Demonstrate the function in a program
// that asks the user to input a string and then passes it to the function.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstring>

// Not sure if I need all libraries but it can't hurt. :)

using namespace std;


// C-String handling function
void Backward (char *);

int main()
{
// define array for letters in a word entered       
char word[41];

// ask user for input
cout << "This program will display the letters of a word entered in backwards order"
       "follwed by a period." << endl;
cout << "Please enter a word not over 40 letters:" << endl;

// display word entered backwards
cin >> word;

cout << "The entered word displayed in reverse is: " << word << endl;

Backward(word);

cout << endl;

       system("Pause");
       return 0;
}


void Backward (char *sentencePtr)

{

       char *p = sentencePtr;
       while ( *p != '\0' )

             ++p;

       while ( p != sentencePtr )

             cout.put ( *--p );
      

}

No comments:

Post a Comment