Reputation:
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;
}
Upvotes: 0
Views: 90
Reputation: 87321
#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;
}
Upvotes: 0
Reputation: 10355
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.
Upvotes: 3
Reputation: 17416
There are at least three problems in your code:
Implementation left as an excercise to the reader.
Upvotes: 3
Reputation: 147
str.length()
is giving you the length of the string, but when you use that as an index into your array, you end up with a array out of bounds error
Upvotes: 2