【问题标题】:Reversing a string in c++ [duplicate]在c ++中反转字符串[重复]
【发布时间】:2016-02-03 22:58:20
【问题描述】:

我开始在 coderbyte 上进行 C++ 挑战。第一个是:

使用 C++ 语言,让函数 FirstReverse(str) 取 str 参数被传递并以相反的顺序返回字符串。

使用下面框中的参数测试功能来测试您的代码 有不同的论点。

它为您提供了以下起始代码,然后您可以对其进行编辑和添加以创建程序:

#include <iostream>
using namespace std;

string FirstReverse(string str) { 

  // code goes here   
  return str; 

}

int main() { 

  // keep this function call here
  cout << FirstReverse(gets(stdin));
  return 0;

} 

我想出了以下几点:

#include <iostream>
using namespace std;

string FirstReverse(string str) {
    cout<<"Enter some text: ";
    cin>>str;
    string reverseString;

    for(long i = str.size() - 1;i >= 0; --i){
        reverseString += str[i];
    }

    return reverseString;

}

int main() {

    // keep this function call here
    cout << FirstReverse(gets(stdin))<<endl;
    return 0;

}

它给了我以下错误:“没有匹配的函数来调用gets” 现在,为什么会发生这种情况,我能做些什么来解决它?感谢您阅读本文,我们将不胜感激。

【问题讨论】:

  • Already available 在标准库中。还提供了一个示例实现。
  • 如果您使用unsigned long,您将拥有更大的范围。从未听说过负长度的字符串。
  • 如果您仍想构建自己的 iterator_loop 使用 reverse_iterators,请参阅example
  • @ThomasMatthews 我想如果这个词是反向的,那么长度是负数? std::string("!tahw").length() == -5 :)
  • @Ben: str.size() 在示例中使用它返回无符号类型 size_t(标准无符号整数)。所以它总是积极的

标签: c++ string reversing


【解决方案1】:

gets 方法在 cstdio 标头中声明。

试试#include &lt;cstdio&gt;#include &lt;stdio.h&gt;

编辑 1:使用 std::string
我推荐使用std::stringstd::getline

std::string text;
std::getline(cin, text);
std::cout << FirstReverse(text) << endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    相关资源
    最近更新 更多