Home > Software design >  This is a program to recursively calculate the reverse of a string but it's not printing anythi
This is a program to recursively calculate the reverse of a string but it's not printing anythi

Time:06-02

What I have done is created a global array to store the reversed string.

#include <bits/stdc  .h>
using namespace std;

char arr[10];
int c = 1;

string Reverser(string z)
{
    arr[c] = z[(z.size() - c)];

    c  ;

    if (c == (z.size()   1))
    {
        return 0;
    }
    else
    {

        Reverser(z);
    }
    return 0;
}

int main()
{
    string z;
    cin >> z;
    string Reverser(z);

    for (int i = 1; i <= z.size(); i  )
    {

        cout << arr[i];
    }

    return 0;
}

I have also tried to dry run it but I can't really find any error.

CodePudding user response:

You can use a std::stringstream and pass it by reference in your recursive function. Also, you can pass the string by reference.

#include <iostream>
#include <string>
#include <sstream>

void reverse(const std::string& a, std::stringstream& ss, unsigned int pos)
{
    ss << a[pos];
    if (pos == 0) return;
    
    reverse(a, ss, pos - 1);
}

void reverse(const std::string& a, std::stringstream& ss)
{
    reverse(a, ss, a.length() - 1);
}

int main()
{
    std::stringstream ss;
    std::string input = "Hello";
    reverse(input, ss);
    std::cout << ss.str() << std::endl;
}
  •  Tags:  
  • c
  • Related