Reversing a string using recursion

Hi,

I am trying to do my homework where I need to reverse a string using recursion. I am able to reverse just the first word of a string, so far. Could someone please help me in determining the best way to make sure all of the words in my string are reversed?




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

string reverseRecursion(string str){
if (str.length() == 1) {
return str;
}else{
return reverseRecursion(str.substr(1,str.length())) + str.at(0);
}
}

int main()
{
string str;
cout<<"Enter the string to reverse : ";
getline(cin, str);

cout<<"The reversed string is : "<<reverseRecursion(str);
return 0;
}


Last edited on
I am able to reverse just the first word of a string, so far.
That's not true. The whole string is reversed.

Enter the string to reverse : abc def ghi
The reversed string is : ihg fed cba
This is working correctly. Maybe you didn't notice or your problem is something else.
Hey guys are you sure? I've been running it since yesterday, and no dice:

Enter the string to reverse : abc def ghi
The reversed string is : cba

I'm new to this website, so I'm not sure if I can include a screenshot. But I promise you, it is only reversing the first word of the string.
Just an update: both of you are right. I am not sure why it is only reading the first word in jGRASP, but when I ran it on an online compiler, it worked beautifully. So it isn't a problem with my code, but I need to figure out what's wrong with jGRASP. Thanks a lot!
The problem is more likely in the input process.
this will read an entire line including spaces.
1
2
3
string str;
cout<<"Enter the string to reverse : ";
getline(cin, str);

but if the getline is replaced with
cin >> str;
then it will read input only until the first space is found.

By the way, the original code doesn't behave very gracefully if it is given a zero-length string to handle. It crashes rather badly.
Last edited on
And jGRASP is also working fine after I restarted it. The program is doing exactly what I need to do in jGRASP. All is well!
Topic archived. No new replies allowed.