can anybody suggest me whats wrong with the code??

#include<iostream>
#include<string>

using namespace std;

void rev_str(string str,int n)
{
	while(str[n]!='\0')
		rev_str(str,++n);
		
	cout<<str[n-1];
}
int main()
{
	string str="shankhs";
	rev_str(str,0);
	return 0;
}

thanks

ok I replaced "while" with "if" and got output as:
sshknahs
????????

I don't really want to think at the moment, but I can post you my string reversing piece of code. Safe and elegant.

#include <string>

string str="shankhs";
reverse(str.begin(), str.end());

ok i know it does but i was practicing recursion and i am struck at this problem the output is:
sshknahs
Why 2 s??????
PLZ help!

Slight modification. Put the cout in the if statement. I'm a little surprised that it works since strings end with '\n' rather than '\0', but it did. You don't want to display that last '\0'. That seemed to be the problem.

#include<iostream>
#include<string>

using namespace std;

void rev_str(string str,int n)
{
    if (str[n]!='\0')
    {
        rev_str(str,++n);
        cout << str[n - 1];
    }
}


int main()
{
	string str="shankhs";
	rev_str(str,0);
	return 0;
}

thanx vernondozier

hi shknahs,
you may also try this:

void rev_str(string str,int n)
{
	if(str[n]!='\0')
		rev_str(str,n+1);
	cout<<str[n-1];
}
// result: shknahs

krs,
tesu

Two points:
C++ string is not required to have NULL terminator ('\0'), but you will find it present under many compilers. One should not use this as a limit on the extent of the string, use the .length() or .size( ) methods.

C-style strings end with '\0', not '\n'. The newline is a character that may be embedded within a string.

Hello,

Sorry to disturb, But i am not able to understand the process in which the string will be reversed i mean.

sky
reversed : yks

But how do we obtain that with the upper code.

Could anyone explain me why cout<< str[n-1] is used and what n is?

Here's a slightly modded version to make things clearer:

#include<iostream>
#include<string>

using namespace std;

void rev_str(string str,int n)
{
    if (n != str.size())
    {
        rev_str(str,++n);
        cout << "n=" << n << " str[n-1]=" << str[n - 1] << "\n";
    }
}


int main()
{
	string str="shankhs";
	rev_str(str,0);
	cin.get();
	return 0;
}

As you can see n is the size of the string, in this case n=7. (seven chars)
You can access a single character from a string like this: str[0] (would be 's' in this case). You know about arrays right?

Now the n-1 is there because you want to access 7 chars, but that's from 0-6. So that's why [n-1], because you want to loop from 0-6 and not from 1-7.

Thanks for the explanation, I dint see the recursion in the first glance but. Again when i checked it out i found it :)

Cool Way Of Getting the String in reverse :)

I personally like Cybulski's version better. (although he/she forgot to mention to #include <algorithm> )In 99% of all cases recursion isn't necessary and only makes a program harder to understand for the programmer (and his/her colleagues).

Besides, if there's a standard function to do the job, why re-invent the wheel?

But for test-purposes and just to tickle the brain, recursion is fun to play around with .

This way or another, you should use iterators, to avoid exceeding string boundaries.

For example:

string str;
string::iterator iter_str = str.begin();

while(iter_str != str.end())
{...}

what i understood is after recursion of end of string it executes the below lines of function calls ( no. of time if callls ) as function call goes to stack
loop.

pl. somebody explain more about this.

#include<iostream>
#include<conio.h>
using namespace std;
#include<string>
int main()
{
    
    /string name="abcdefgh";
    char *ptr;
    ptr=&name[0];
    while(*ptr !='\0')
    {
               ptr++;
               }
               while(ptr!=&name[0])
               {
                  cout<<*(ptr-1);
                  ptr--;
                  }
    getch();
    }

This is my first attempt writing a recursive program.

i have choose some constraints like:
1)the string reverse function call should have only one argument i.e the pointer to the string,
2) string should be reversed in the same position instead of using the another string or writing to output..

here is my code flow.. correct me if needed:

#include <iostream>

using namespace std;

int reverse_String( char *);

main()
{
   char string1[20] ="Welcome";
   int i;
   cout << "String passed: " << string1 << endl;
   reverse_String( string1);
   cout << "Reversed string is: " << string1 << endl;
   cin >> i;
}

int reverse_String(char * string1)
{
      char temp;
      int len =strlen(string1);
      static int counter;
      if(counter < len/2 )
      {
          //swap the characters
          temp = string1[counter];    
          string1[counter] =string1[len-counter-1];
          string1[len-counter-1] = temp;

          counter++;
          reverse_String(string1);  
      }
      else
      {
          return(0);
      }  
}

Thanks,
Venugopal.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.