这是一个递归计算字符串反转的程序,但它不打印任何东西

This is a program to recursively calculate the reverse of a string but it's not printing anything

我所做的是创建一个全局数组来存储反转的字符串。

#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;
}

我也试过烘干运行但是实在找不到什么错误。

您可以使用 std::stringstream 并在递归函数中通过引用传递它。此外,您可以通过引用传递字符串。

#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;
}