Recursive Reversal Function

I'm currently working on a code for taking in a character array, a[], and it's length n. It's then supposed to reverse all of the letters and return them as a string

1
2
3
4
5
6
7
8
9
10
11
12
string RevIt(char a[], int n)
{
	string ret, cur;
	if(n==0)
		return ret+=a[n];
	else
  	{
    	 ret+=RevIt(a,n-1);
		 cur=a[n];
		 return cur;
  	}
}

it's not throwing anything out, and i'd just like someone to give me advice/help with it. Thanks!
This is your code
1
2
3
string RevIt(char a[], int n){
  return string(a[n],1);
}
how would i go about changing my code so that it reverses the entire char array into a string? I can only get it to return the first character at the moment
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <sstream>
using namespace std;

string RevIt(char a[], int n)
{
  stringstream stream;
  for(int i=(n-1);i>=0;i--)
    stream << a[i];
  return stream.str();
}
While that does indeed work(I actually had it like that before), I need to make this function do it via recursion
and recursive:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

#include <iostream>
#include <sstream>
using namespace std;

string RevIt(char a[], int n)
{
	stringstream stream;

        if( n<=0 )
             return "";

	n--;
	stream << a[n] ;
	if(n > 0)
		stream << RevIt( a , n );
  
	return stream.str();
}

int main()
{
	cout << RevIt("ABCD",4) << "\t" << RevIt("123456789",9) ;

	while(1);

    return 0;
}



edit: actually this will only work once;)

edit 2: fixed
Last edited on
RevIt("",0);
Crash....
Easy fix?

Add this on line 8:
1
2
if( n <= 0 )
    return;
Your right, I was being lazy...
lol! Not too lazy, I learnt something from your effert to code the above (:
Good to hear that!
Sorry if I'm hijacking this thread, but...

In the above code, wouldn't it be better to create the stringstream as a static variable, so that it's just changed rather than recreated each run of the function?

Depending on the size of the char-array, there could be an efficiency issue?
I did that just moments ago... The point is the stream cannot be reset when it is completed...
This causes the result to be deleted before it is returned...
Topic archived. No new replies allowed.