I'm trying to reverse a string in pairs
Example: input - heaven
output - ne va eh
My code seems to be right until the last for loop...
That's where I need help
Here's my code:

#include <iostream>
#include <string>
using namespace std;
string revString(string user);
int main()
{
    string user;
    cout<<"Enter a random text"<<endl;
    getline(cin,user);
    unsigned int length=user.length();
    while (length%2 == 1)
    {
        cout<<"enter the text with even amount of letters"<<endl;
        getline(cin,user);
        length = user.length();
    }

        string revstr = revString(user);
        cout<<revstr;


       return 0;
}
string revString(string user)
{
    string rev;
    for(int i =1; i<=(int)user.length();i+=2)
    {
        rev = user.length[i+1];
        rev = user.length[i];
    }
    return rev;
}

Recommended Answers

All 5 Replies

Your code compiles fine? Because length is a function and you are trying to use it as an array

user.length[i]

Your code compiles fine? Because length is a function and you are trying to use it as an array

user.length[i]

|29|error: invalid types '<unresolved overloaded function type>[int]' for array subscript|
|30|error: invalid types '<unresolved overloaded function type>[int]' for array subscript|
||=== Build finished: 2 errors, 0 warnings ===|

for the last 2 reverse lines
this 2 lines:
rev = user.length[i+1];
rev = user.length;

That is because length is a function, not an array. You cannot have an index for a function. I think you are trying to get the character at that index, for that you can directly use [] with a string.

user[i];

And your logic is flawed, when you'll run the program you'll figure it out.

better prefer pass by reference rather than pass by value
there are several easier ways to do this

std::copy(user.rbegin(), user.rend(), std::back_insert(rev) );

or

std::reverse_copy(forward_.begin(), forward_.end(), std::back_inserter(backward_) );

or

std::string forward = "abcdefg"
std::string backward(forward.rbegin(), forward.rend() );

I would prefer the last way, it is easier to understand(for me) and should be more effective

It is not a bad idea to do some practice by hand crafted codes
But prefer the standard algorithms or the function provided by the
containers would be better in most of the cases.

forgot one thing
if you only want to reverse the string
you don't need another string
just use

std::reverse(user.begin(), user.end() );

if you need hand crafted codes, try this

void reverse_test( std::string::iterator first, std::string::iterator last)
{
  while ((first!=last)&&(first!=--last))
  {
    std::swap(*first,*last);
    ++first;
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.