I will present two forms:
- the STL way.
- the traditional way.
the STL way Code:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
//Optional functions: depends on IDE. void wait_for_enter();
int main()
{
string sOriginal("123321");
string sReversed(sOriginal);
reverse(sReversed.begin(), sReversed.end());
cout<<sOriginal<<endl;
cout<<sReversed<<endl;
if(sOriginal == sReversed)
{
cout<<"Palindrome detected!"<<endl;
}
wait_for_enter();
return 0;
}
//--------------------------------------------------- void wait_for_enter()
{
cout << "press <enter> to continue...";
// Reset failstate, just in case.
cin.clear();
string line;
getline( cin, line);
} the traditional way Code:
#include <iostream>
#include <string>
using namespace std;
//Optional functions: depends on IDE. void wait_for_enter();
int main()
{
string sOriginal("123321");
string sReversed;
unsigned size = sOriginal.size();
for(unsigned i=0; i < size; ++i)
{
//Traverse from sOriginal[5] to sOriginal[0] *IF* sOriginal.size() == 6.
sReversed += sOriginal[size-i-1];
}
cout<<sOriginal<<endl;
cout<<sReversed<<endl;
if(sOriginal == sReversed)
{
cout<<"Palindrome detected!"<<endl;
}
wait_for_enter();
return 0;
}
//--------------------------------------------------- void wait_for_enter()
{
cout << "press <enter> to continue...";
// Reset failstate, just in case.
cin.clear();
string line;
getline( cin, line);
}