user3332894
user3332894

Reputation:

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

Upvotes: 0

Views: 90

Answers (4)

pts
pts

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

stefan
stefan

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

kauppi
kauppi

Reputation: 17416

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.

Upvotes: 3

109
109

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

Related Questions