【问题标题】:Stuck in C++ data structure program [closed]陷入C ++数据结构程序[关闭]
【发布时间】:2013-10-25 09:35:25
【问题描述】:

编写一个程序,提示用户输入字符串并使用递归函数向后打印字符串。不要使用任何全局变量;使用适当的参数。你能给我一些提示吗,比如伪代码?

int stringbackwards(string a){                  
if()


else


}


int main(){

    string name;

    cout<<"Write a name: ";           
    cin>>name;

    cout<<"Backwards "<<stringbackwards(name);

    return 0;
}

【问题讨论】:

  • 人们会为你尝试过的事情提供帮助,但请不要指望我们会给你代码。
  • 没有人会帮你做作业。

标签: c++ data-structures


【解决方案1】:

你为什么要使用递归呢? c++ 中有一个很好的概念叫做迭代器,它已经实现了这个功能:)

http://www.cplusplus.com/reference/string/string/rbegin/

所以在你的情况下:

cout<<"Backwards ";
for (std::string::reverse_iterator rit=name.rbegin(); rit!=name.rend(); ++rit)
{
    cout << *rit;
}

但为了使其递归,我会这样做(伪代码)。

function backwards(std::string& name, unsigned int length)
{
    unsigned int length = name.length();
    unsigned int currLength = length - 1;

    if (length > 0)
    {
         backwards(name, currLength);
    }

    std::cout << name[length - currLength - 1];
}

【讨论】:

  • 也很正确,只是这可能是一个家庭作业问题。
  • 因为作业,我不得不使用递归。 ;) 我不认为该函数必须返回一个 int。
  • 那么你的家庭作业;)
  • 见上文 - 类似但未经测试。
【解决方案2】:

提示:

假设字符串是“abcd”。您想打印“dcba”。换句话说,您首先打印最后一个字母。

因此您将首先深入递归,然后在返回后打印字母'a'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2014-10-29
    • 2018-08-30
    相关资源
    最近更新 更多