[英]String reverse program crashes
I am making a program that is reversing a given string.我正在制作一个反转给定字符串的程序。 but i don't know why my program is crashing.
但我不知道为什么我的程序崩溃了。 Help will be highly appreciated instead of criticism.
帮助将受到高度赞赏而不是批评。 Thanks!
谢谢!
#include <iostream>
#include <string>
using namespace std;
string reverse(string );
int main()
{
string str;
cout << "Enter a string"<<endl;
getline (cin, str);
reverse(str);
}
string reverse (string str)
{
string str1;
for(int i = str.length(); i >= 0; i--)
{
str1[i] = str[i];
}
return str1;
}
There are at least three problems in your code:您的代码中至少存在三个问题:
Implementation left as an excercise to the reader.实现留给读者作为练习。
You do not need to reinvent the wheel, use an algorithm!你不需要重新发明轮子,使用算法!
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
string str;
cout << "Enter a string"<<endl;
getline (cin, str);
std::reverse(str.begin(), str.end());
}
You can read more about std::reverse
on cppreference.com .您可以在cppreference.com上阅读有关
std::reverse
更多信息。
str.length()
为您提供字符串的长度,但是当您将其用作数组的索引时,您最终会遇到数组越界错误
#include <algorithm>
#include <string>
void reverse_in_place(std::string &str) {
std::reverse(str.begin(), str.end());
}
std::string copy_and_reverse(std::string str) {
std::reverse(str.begin(), str.end());
return str;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.