String swapping

I should write a code that takes a name and a last name from user,and than outputs that full name reversed, like that:

John Smith -> htimS nhoJ

But I get "Je htSmi n". What did I do wrong?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>
using namespace std;


int main()
{
	cout << "Enter your first name please: ";
	string Name;
	getline(cin,Name);
	
	cout << endl<<"Enter your second name: ";
	string LastName;
	getline(cin,LastName);

	string BlankSpace=" ";
	
	string FullName;

	FullName=Name+BlankSpace+LastName;
	cout <<FullName<<endl;
	int DoubleLess=FullName.length() / 2;

	cout<< endl<<DoubleLess<<endl;
	int Length=FullName.length();

	int Number=Length +1;
	for(int i=1;i<DoubleLess;i++)
	{
		swap(FullName[i],FullName[Number]);
		Number--;
	}

	cout<< "Your name changed is " << FullName<<endl;

	return 0;

}
Try this:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44


#include <iostream>
#include <string>

using namespace std;


int main()
{
	cout << "Enter your first name please: ";
	string Name;
	getline(cin,Name);
	
	cout << endl<<"Enter your second name: ";
	string LastName;
	getline(cin,LastName);

	string BlankSpace=" ";
	
	string FullName;

	FullName=Name+BlankSpace+LastName;
	cout <<FullName<<endl;

	int Length=FullName.length();
	cout<< endl<<Length<<endl;
	
	for(int i=0;i<Length;i++)
	{
		swap(FullName[i],FullName[Length-1]);
		
		Length--;
	}

	cout<< "Your name changed is " <<FullName<<endl;
	
	


	return 0;

}
Array index should go from 0 to length-1
Accessing outside that is an error.
Of course MR:ne555
Thank you very much.
And by the way,for loop goes like this: for(int i=0; i<Length/2 ;i++),because if you keep for loop swapping characters for full length,you will get the same thing you started with,original full name.
Problem solved,thank you very much.
Topic archived. No new replies allowed.