#include <iostream>
using namespace std;
string reverse(string str, int size) {
if (size == -1)
return "";
else
{
char a;
a = str[size];
return a + reverse(str, size - 1);
}
}
int main() {
int size;
cout << "the size of the string : ";
cin >> size;
string str;
cout << "enter the word : ";
cin >> str;
cout << reverse(str, size);
}
答案 0 :(得分:2)
由于您使用std::string
,因此无需指定字符串的大小,而是使用std::string::size()
或std::string::length()
成员函数。此外,当a = str[size];
等于字符串的大小时,size
会出现问题,因为您执行了超出限制的访问(请记住C ++使用从零开始的索引)。您可以大量简化代码,最后以
#include <iostream>
#include <cstddef> // for std::size_t
using namespace std;
string reverse(string str, std::size_t pos) {
return (pos == 0 ? "" : str[pos - 1] + reverse(str, pos - 1));
}
int main() {
string str;
cout << "enter the word : ";
getline(cin, str); // allow for spaces in the string
cout << reverse(str, str.size()) << endl;
}
此处,我使用cin >> str
而不是getline(cin, str)
,因为cin
读取第一个空格,而getline
允许读取string
s那些空间。
答案 1 :(得分:1)
将函数reverse
的实现更改为以下内容。
string reverse(string str ,int size){
if (size==-1)
return "";
else
{
char a;
a=str[size];
if (' ' == a )
return reverse(str,size-1)
else
return a+reverse(str,size-1);
}
}
或者,对输入进行一些预处理。