Reverse name (Strings)

Hello guys just trying to reverse a users input name here and its not working at all and i cannot understand it, Would appreciate some input thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void reverse(string& name, int letters)
{
	char hold;
	int n = 0;

	for(int i = letters - 1; i >= 0; i--)
	{

		hold = name[n];

		name[n] = name[i];

		name[i] = hold;

		n++;
	}
}


Letters int just represents how many letters are in the users name.

So i want it to just take the first character and replace it with the last and since both n and i go on to meet each other i dont see why it doesnt at least PARTIALLY work? I could understand if there is a bug when they get to the middle of the name but this works not at all!
That's because you swap each pair of characters twice. For example, the first letter is switched with the last one at the beginning of the loop and then again at the end of the loop.
I dont think i get it - N goes plus plus so shouldn't it then start replacing the second letter with the second to last letter on the second itteration of the loop?

At the beginning i = [14] and n = [0]

Lol sorry for the vague 14 - i am using my name: "Vlad_Lopatinsky" As the test string so thats where i get 14 from
Last edited on
Well, take a look at the string as the loop progresses - I suppose you'll see it now.
i=14, n=0: ylad_LopatinskV
i=13, n=1: ykad_LopatinslV
i=12, n=2: yksd_LopatinalV
i=11, n=3: yksn_LopatidalV
i=10, n=4: yksniLopat_dalV
i=9, n=5: yksnitopaL_dalV
i=8, n=6: yksnitapoL_dalV
i=7, n=7: yksnitapoL_dalV
i=6, n=8: yksnitopaL_dalV
i=5, n=9: yksniLopat_dalV
i=4, n=10: yksn_LopatidalV
i=3, n=11: yksd_LopatinalV
i=2, n=12: ykad_LopatinslV
i=1, n=13: ylad_LopatinskV
i=0, n=14: Vlad_Lopatinsky

UGH! So it does partially work thats good.. Thanks so much Athar im still pretty confused but i think i will sleep on it tonight - its 1 am here
This is an example straight from my book, maybe you could take a look and it will explain things a little?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
int main()
{
using namespace std;
cout << “Enter a word: “;
string word;
cin >> word;
// physically modify string object
char temp;
int i, j;
for (j = 0, i = word.size() - 1; j < i; --i, ++j)
{ // start block
temp = word[i];
word[i] = word[j];
word[j] = temp;
} // end block
cout << word << “\nDone\n”;
return 0;
}
Yup thanks guys i woke up today and went ahead and did the same exact fix. @Athar i am pretty jealous of your mad skillz to see these things so quick!
Topic archived. No new replies allowed.