Search code examples
c++stringfunctionrecursion

Reversing a string using with a recursive function in C++


To explore my understanding of recursion, I am attempting to reverse a string by use of a recursive function. This seems like it should be more simple than it is for me right now. Can any one tell me what I am doing wrong. When I execute the code below, it results in a blank line. I looked around on here for similar topics but every thing is in other languages... much to my surprise.

#include <iostream>
#include <string>

using namespace std;


/**
    Recursivly reverses a string
    @param return last_char, the last character currently in the string
    @param go, the recursive function to return the character and continue     within the function
    **/
char string_reverse(string word)
{

    if (word.length()-1 > 0)
    {
    char last_char = word[word.length()-1];
    word.erase(word.length()-1);
    char go = string_reverse(word);
    return go;

    }

else 
    return false;

}


int main()
{
cout << "Enter a string: ";
string input;
getline(cin, input);
string last;
last = last + string_reverse(input);
cout << last << endl;

/*char fig = string_reverse(input, fig);
cout << fig << endl;
*/

system("pause");
return 0;
}

Solution

  • You need to return string, also you need to prepend extracted char to returned value

    string string_reverse(string word)
    {
        if (word.length() - 1 > 0)
        {
            char last_char = word[word.length()-1];
            word.erase(word.length()-1);
            string go = string_reverse(word);
            return go.insert(0, 1, last_char);
        }
        else
            return "";
    }