#include <iostream>
usingnamespace std;
int main()
{
usingnamespace 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.
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?