There are several erros in your implementation like the other answers have already pointed out, the biggest one is that you are passing the string by value, so you are making changes on a copy of the original string and second the reason why the loop wont end is because you are using a while loop to break the recursion, but you are only incrementing "i" when you call reverse recursively, which mean that in the first calls to reverse "i" is not incremented, so the while will only break on the last call of the recursion, but then when it returns from it, it gets stuck in the previous call because "i" in that scope will never be greater than "l". that can be easily fix by changing the the while for an if instruction. Then your code will work as expected.
However, if you want to print your string backwards you should use the reverse iterators on the string class to traverse it in reverse order and then just print the characters as you go:
for (std::string::reverse_iterator rit = str.rbegin(); rit != str.rend(); ++rit)
cout << *rit;
If you are using C++ and the string class, you should use its poweful features to your advantage.
If you are just doing an exercise on recursion, I dont quite understand what you are trying to accomplish exactly, but if I were to write a string backwards using recursion I would do something like this:
void reverse(string& s, int i = 0)
{
// Break the recursion.
if(i >= s.size())
return;
char ch = s[s.size() - (i + 1)];
cout<< ch << endl;
++i;
reverse(s, i);
}
reversefunction to return the reversed string and not do any printing at all.whilewithifand just include reverse in it .chto change after the recursive call. Why?