简体   繁体   中英

How to return a string in reverse order

I'm trying to make a basic program that gets a string from input and returns the string in reverse. I made code already, but I keep getting a runtime error every time I enter a string. Suggestions?

#include <iostream>
#include <string>

using namespace std;

void flipString(const string& s, string& s2)
{
    int c = 0;

    for (size_t i = s.length() - 1; i >= 0; i--)
    {
        s2.insert(c, 1, s[i]);
        c++;
    }
}

int main()
{
    string str;
    string str2;

    cout << "Enter string: " << endl;
    getline(cin, str);

    flipString(str, str2);

    cout << "\n\n" << "Flipped string: " << str2;

    return 0;
}
#include<algorithm>
//...
str2 = str1
std::reverse(str2.begin(),str2.end()); 
void flipString( const std::string &s, std::string &s2 )
{
   s2.assign( s.rbegin(), s.rend() );
}

If you want to use a loop then the function can look the following way

void flipString( const std::string &s, std::string &s2 )
{
   s2.clear();
   s2.reserve( s.size() );

   for ( std::string::size_type i = s.size(); i != 0 ;  )
   {
      s2.push_back( s[--i] );
   }
}

Or if you want to use standard algorithms then you can write:)

#include <algorithm>
#include <iterator>

void flipString( const std::string &s, std::string &s2 )
{
   s2.clear();
   s2.reserve( s.size() );

   std::reverse_copy( s.begin(), s.end(), std::back_inserter( s2 )  );
}

The logic implemented in the question would do the job of reversing a string (although there might be many other, more efficient, ways to do it). However we get a segmentation fault when we run it.

We get a segmentation fault when an object tries to access memory which does not belong to it.

In the above case, the function flipString takes const string& s as input and then allocates the content inside it using s[i]. The [] operator would return a reference to the char. Thus you are allocating the reference of a const object. Hence it faults when you try to access it.

Try the following flipString method and it should work.

    void flipString(const string& s, string& s2)
    {
        int c = 0;
        for (int i = s.length() - 1; i >= 0; i--)
        {
            const char current_char = s[i];
            s2.insert(c, 1, current_char);
            c++;
        }
    }

Please correct me if I am wrong.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM