Scary

Hey, I know this isn't working because of the "i =toReverse.length();" in the for loop. I guess you can't use a function like this but how would I do what I'm trying to do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

string toReverse, bob;
int i;

string reverse(string toReverse);

int main()
{
    cout << "Enter a string: ";
    cin >> toReverse;
    cout << "Reverse = " << reverse(toReverse);
    return 0;
}

string reverse(string toReverse){
    for(i=toReverse.length();i>=0;i--){
        bob+=toReverse.at(i);
    }
    return bob;
}
1. Delete line 4, toReverse should be inside main and bob should be in reverse
2. Delete line 5, it should be inside reverse
3. You need to swap the first and last characters, then move one in and swap those, etc. or you can just reconstruct a new string from the old one:
1
2
3
4
5
6
7
8
9
std::string reverse(const std::string &to)
{
    std::string rev;
    for(std::string::reverse_iterator it = to.rbegin(); it != to.rend(); ++it)
    {
        rev += *it;
    }
    return rev;
}
Last edited on
But if I move toReverse then main can't use it
closed account (zb0S216C)
Of course it can. Who told you it can't? It just makes i & toReverse local to main( ).

Wazzak
Last edited on
Oh sorry, I thought you said toReverse should be inside reverse
And I wish I could use the rest of what you said but it's for an assignment and we haven't gone over any of that. Theres not any way to initialize i to the value of toReverse.length() without changing the rest is there?
closed account (zb0S216C)
You can initialise ::i with ::toReverse.length( ), but the initial value would be zero because ::toReverse has no characters stored within it.

Initialisation of ::i:
 
int i( 0 ); // Equivalent to: int i = 0; 


Wazzak
Alright thanks, I'll see what i can do
You are very close, there are really only two changes you need to make for it work. Change cin >> toReverse
to getline(cin,toReverse);//using >> you wont get the whole string
And you need to subtract 1 from toReverse.length(), you're trying to read one to many characters. You should also follow notes 1 and 2 of LB's post.
Last edited on
Topic archived. No new replies allowed.