Shouldn't this successfully reverse the string?

Write your question here.
I have a feeling that i've made some miscalculation here. I was certain that I could reverse a string via implementing the following solution;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int j=7;  
  int main ()
{
    
    
    
 string FirstReverse = "reverse";
    cout << FirstReverse << endl;

   
 for (unsigned int i=0; i < FirstReverse.size(); ++i)
    {
        FirstReverse[i]=FirstReverse[--j];
    }


    cout << FirstReverse << endl;

    return 0;
}


unfortunately, my resulting output is as follows;
reverse
esrerse

I'm convinced that i've misunderstood the effect that would come about by pairing a decreasing variable with an increasing one, and am wondering if anyone can help me identify alternative solutions, or help me understand what went wrong with this one.

Any help is appreciated!
You assign the last letter of your string to the first letter.
Then you assign the next-to-last letter of your string to the second letter.

At this point the original value of the first and second letter are lost to you. Time for a new algorithm.
Two problems:

(1) You are supposed to swap the values at i and j, but you are only copying the value at j to i:

  reverse
  esrever
 ---------
  esrerse


(2) You should stop at i >= j, otherwise you'll reverse it twice.

Hope this helps.
Last edited on
Well, you could easily create a temporary variable to hold the value at FirstReverse[i], so that when you switch it with FirstReverse[FirstReverse.length - i - 1], you can replace the other variable with what was originally in FirstReverse[i].
Why not just stop reversing at the half-way point? That would be much easier than fixing errors after the fact.
I've read through the feedback, and I believe that Duoas's solution has the best chance of being compatible with my intended outcome.

I'm still new at this, and have been unable to properly cease the reversal process at a half-way point.

I attempted a nested "If" loop, and this did not seem to stop the programs completion. I still have much to learn.

The "if" loop looked like this:
1
2
3
4
 if (i == 3) 
{ 
break; 
}
1
2
3
4
5
6
7
8
string s = "Hello world!";
int i = 0;
int j = s.length() - 1;
while (i < j)
  {
  do something here
  don't forget to update i and j
  } 

:O)
Topic archived. No new replies allowed.