Reversing a string using recursion

Feb 17, 2016 at 3:34am
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 Feb 17, 2016 at 3:36am
Feb 17, 2016 at 8:53am
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
Feb 17, 2016 at 10:15am
This is working correctly. Maybe you didn't notice or your problem is something else.
Feb 17, 2016 at 3:07pm
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.
Feb 17, 2016 at 3:15pm
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!
Feb 17, 2016 at 3:20pm
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 Feb 17, 2016 at 3:21pm
Feb 17, 2016 at 3:21pm
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.