0

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;
}
1
  • After fixing the problems mentioned in the answers, please change the string str argument to const string &str to avoid the unnecessary copying of the argument. Commented Apr 23, 2014 at 18:53

4 Answers 4

3

There are at least three problems in your code:

  1. You need to have a string with a length prior to accessing it with [], especially when writing to it.
  2. The code is trying to access out of bounds.
  3. The algorithm is just copying the string in reverse order, not reversing the string itself.

Implementation left as an excercise to the reader.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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

Comments

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

1 Comment

some text to put the code in context would be welcome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.