reversing C string using pointers

I'm trying to write a program that reverses C strings using pointers. So far I have something like 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>

using namespace std;


int main()
{
	using namespace std;

	char control = 'y';//this variable is used by user to stay in or exit out of do-while loop

	do
	{
		char *rear, *front;
		cout << "Enter a string of characters: ";
		char sentence[10];
		cin >> sentence;
		
		short i(0), j(0);
		char temp;
		front = sentence;
		rear = &sentence[strlen(sentence)-1];

		while(rear+j > front+i)
		{
			/*
			//testing
			cout << *(front+i);
			cout << *(rear+j);
			char next;
			cin.get(next);
			*/
			
			temp = *(front+i);
			sentence[i] = *(rear+j);
			sentence[j] = temp;

			i++;
			j--;
		}
		cout << sentence;
		

		cout << "\nWould you like to run the program again? (Y/N): ";
		cin >> control;
		while ((control != 'y') && (control != 'n'))
		{
			cout << "Incorrect input. Would you like to run the program again? (Y/N): ";
			cin >> control;
			control = tolower(control);
		}
		cin.ignore();
		cin.clear();
	}while(control == 'y');
	
	cout << "Press key to exit: ";
	char exit;
	cin >> exit;

	return 0;
}


The program seems to work with strings which happen to be palindromes (for some reason) but not with strings in general. What am I doing wrongly? My book unfortunately only gives 1 or 2 examples dealing with pointers. It's usually a pretty good when it comes to explaining most topics but for some reason the author does a bad job of covering this specific topic. Please help.
I also get some run-time error saying that the stack around "sentence" was corrupted.
Reversing a string:

a --> s
b --> s + strlen() - 1

Hello world!
a          b

Swap *a and *b, adjust a and b:

!ello worldH
 a        b

Swap *a and *b, adjust a and b:

!dllo worleH
  a      b

Swap *a and *b, adjust a and b:

!dllo worleH
   a    b

Etc. When do we stop?

Hope this helps.
Last edited on
Topic archived. No new replies allowed.