Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Revise Reverse Routine

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Can anyone please revise the following program and yet it will still do the same function. Thanks.


#include <iostream>
#include <string.h>
using namespace std ;

void strReverse ( char *pString ) ;

int main ()
{
char ch[20] ;

cout << &quot;Please enter the string you want to reverse: &quot; ;
cin.getline ( ch, 20 ) ;

strReverse ( ch ) ;
cout << &quot;Your string reversed is: &quot;
<< ch
<< '\n' ;

return 0 ;
}

//
******************************************************************************

****
// Routine: strReverse ()
// Programmer: Luis Lugo
// Purpose: This routine reverses a string
// Parameters: pString - type char * : The string to be left trimmed in
place.
// Returns: Nothing.
//
******************************************************************************

****

void strReverse ( char * pString )
{
int length = strlen( pString ), i, k ;
char tempCh ;

for ( i = 0 , k = length - 1 ; i < length / 2 ; i++ , k-- )
{
tempCh = pString ;
pString = pString [k] ;
pString[k] = tempCh ;
tempCh = NULL ;
}
pString [length] = '\0' ;
}
 
Code:
void strReverse(char *pString) {
   int i,k;
   char temp;
   for(i=0,k=strlen(pString)-1;i>=k;i++,k--) {
      temp = pString[i];
      pString[i] = pString[k];
      pString[k] = temp;
   }

Instead of manipulating the string values, you were manipulating the main string pointer itself. Be very careful about pointers. Oftimes, as in the above example, it is safer to use the array notation. Otherwise, use the dereferencer to access the value of the location that the pointer is pointing at, not the value of the pointer. Also, you don't need to reassign the terminator character to the new string, because it is still there from the original string.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top