在 C++ 中反转字符串

Reversing a string in c++

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

Using the C++ language, have the function FirstReverse(str) take the str parameter being passed and return the string in reversed order.

Use the Parameter Testing feature in the box below to test your code with different arguments.

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

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

}

它给我以下错误:"No matching function to call to gets" 现在,为什么会发生这种情况,我该怎么做才能解决它?感谢您阅读本文,我们将不胜感激。

gets 方法在 cstdio header 中声明。

尝试#include <cstdio>#include <stdio.h>

编辑 1:使用 std::string
我建议使用 std::stringstd::getline.

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