string reverse recursion

My program is written as shown below, but I can't make it return the opposite word even though I think everything is correct. What is the problem? Input word is word and should return drow. Thank you for the help.
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
#include <iostream>
#include <string>

using namespace std;

string var = "";

string reverse(string str)
{
  if (str.length() == 0)
    return str;
  else
  var.append(str.substr(str.length() - 1));
  cout << var << endl;
  str.erase(str.length() - 1);
  return reverse(str);
}

int main()
{
  string word;
  cout << "Input word: " << endl;
  cin >> word;
  cout << "Reversed word: " << reverse(word) << endl;
}

Output:
Input word:
word
Reversed word: d
dr
dro
drow

Last edited on
1
2
  if (str.length() == 0)
    return str;

You're returning an empty string here.

Also, don't use global variables. If you want a variable to last until the end of the program, use static.
1
2
3
4
5
string reverse(string str)
{
    static string var = "";
    // ...
}
Last edited on
@integralfx Thank you. I know that, but why do I get this empty string? How do I avoid this situation?
1
2
  if (str.length() == 0)
    return str;

This is the base case, that ends your recursion. Therefore, after your recursion ends, it will return an empty string.

cout << var << endl;
This seems to be printing the correct string every time the function calls itself.

PS: It's actually easier than you think.
Yeah, I know that the second argument prints the correct string, but maybe I have to change something in the else function, so the empty string isn't returned or will it be always returned cause then maybe i could use another if statement to exclude it from printing the empty string or change something in the else statement?
Last edited on
1
2
3
4
5
6
std::string reverse( std::string str )
{
    if( str.size() < 2 ) return str ; 
    else return str.back() + reverse( str.substr( 1, str.size() - 2 ) ) + str.front() ;
                // last character + reverse of the the middle n-2 characters + first character
}

Input word: 
word
d
dr
dro
drow
Reversed word: 


The output before "Reversed word: ", is what you expect.
Where does that output come from?
But why does the function return an empty string?
How can you change the base case so that it returns what you expect?

Sorry to beat around the bush, but I'm a firm believer that solving the problem yourself will be more worthwhile than for someone to tell you the solution.
Last edited on
Thanks.
Topic archived. No new replies allowed.