Recursive function

Hi I am relatively new to C++. I am trying to write a program that will compute the reverse of a strin (i.e. flow will return as wolf). The hint I have been given is: Reverse the substring starting at the second character, then ass the first character at the end.

I have attempted to write the program several times. I thought I finally had one that worked. This program compiles and lets you enter a string but then it will just say "Segmentation fault"

Here is my source code:
#include <iostream>
#include <string>
using namespace std;

string reverse(string str)
{
string last (1, str[str.length()-1]); // new string of last character
string reversedstr = reverse(str.substr(0,str.length()-1)); //reversing
string flip= last+reversedstr;
return flip;
}

int main()

{
string str;
string flip;

do {
cout << "Please enter a string" << endl;
cin >> str;
}
while (str.length() ==0);

reverse(str);

cout << "Your string reversed is " << flip << endl;
return 0;
}


Any help with how to fix it would be great!!!
You must assign the value(string in this case) returned by function reverse to flip in the main function.

Like this: flip=reverse(str);

The actual runtime error is with: string last (1, str[str.length()-1]); // new string of last character

And please use code tags(<>) next time you're posting a code.

Hope it helps,
Aceix.
Last edited on
Your function has no condition that determines when the recursion shall be stopped. This is the reason of the segmentation fault.

The realization can be simpler without creating local variables

1
2
3
4
5
std::string reverse( const std::string &s )
{
	if ( s.size() < 2 ) return ( s );
	else return ( s[s.size() - 1] + reverse( s.substr( 0, s.size() - 1 ) ) );
}


Here the condition that determines that the recursion shall be stopped is

s.size() < 2
Last edited on
Thank you guys for your help however Aciex with your suggestion I still got the same error, so the problem is in my function somewhere. And vlad from moscow I only got more compiler errors with your suggestion.

This leads me to think that I am taking the hard road trying to write this function does anyone have any more simple thoughts on how to write this recursively but without any loops??
Topic archived. No new replies allowed.