0

I just want to clarify that I've looked for guidance else where but none have been any help to my specific problem. All of the ones I have seen are either passed by a char array or a regular variable. All of the solutions just print out the reverse form without actually changing the variable. But as my title says, I need help to change the variable of the string into it's reversed form. So I'm just looking for some direction on how to do it not to be given the answer because I won't learn anything. I'm just a beginner and need help. If someone could provide it would much appreciated.

In an attempt to try to complete this task, I decided first to just simply recursively print the reverse form of a string. This is the code I have:

void reverse(string& word)
{
    int n = word.length();
    if (n == 1)
        cout << word << endl;
    else
    {
        cout << word[n - 1];
        string b = word.substr(0, n - 1);

        reverse(b);
    }
}

This code works. I've tried to replace string b with word and place it into the reverse function when it's called but it only gives word the first letter of the word I'm trying to reverse as it's value because when I print it in the main function that is all it gives me.

For example:

string n = "random";
reverse(n);
cout << n;

It should give me modnar but it only gives mer when it is printed. Can someone guide me in the right direction on how to change the value of the reference variable to it's reversed form?

amateur
  • 1
  • 1
  • @ πάντα ῥεῖ This isn't a duplicate of the other page because it is different in the fact I use a reference variable and need to change in into it's reversed form. Mine is also a void function. It does not return a value. – amateur Mar 31 '16 at 16:54
  • Add `word = word.substr(n - 1, 1) + b;` line after `reverse(b);`. – Ivan Gritsenko Mar 31 '16 at 16:57
  • @Ivan Gritsenko Thank you! Can't believe I didn't think of that. – amateur Mar 31 '16 at 17:07

0 Answers0