"Lorin Leone" <le********@hotmail.com> wrote in message
news:92**************************@posting.google.c om...
Can anyone help me modify the program so that it recognizes strings
like "Anna" as palindromes. To make the program "case-insensitive."
using the built-in C++ function "toupper". and so that it recognizes
strings like
"race car" as palindromes, have the program ignore spaces in the input
string.
Here is my code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#include "Stack.h"
#include "queue.h"
int main()
{
Stack the_stack;
Queue the_queue;
char cur_char;
char tos;
char foq;
bool s;
bool is_pal;
cout << "input string: ";
cin.get(cur_char);
while (cur_char != '\n')
{
the_stack.push (cur_char));
the_queue.enqueue (cur_char);
cin.get (cur_char);
}
is_pal = true;
while(not the_queue.is_empty() and is_pal)
{
the_stack.get_top(tos, s);
the_queue.get_front(foq, s);
the_stack.pop(s);
the_queue.dequeue(s);
if(tos != foq)
is_pal = false;
}
cout << endl;
if( is_pal )
cout << "String is a palindrome." << endl;
else
cout << "String is NOT a palindrome." << endl;
return 0;
}
Okay, first I'd suggest the following code which is more efficient to check
for a palindrome:
string Test;
cin >> Test;
bool bFlag = true;
string::iterator IterFw = Test.begin();
string::reverse_iterator IterBw = Test.rbegin();
while( *(IterFw++) == *(IterBw++) && IterFw != Test.end() ) {
bFlag = false;
}
if( !bFlag )
cout << "it's a palindrome" << endl;
else
cout << "it's NOT a palindrome" << endl;
Some more hints to solve your problem - before you feed the string to the
palindrom algorithm you have to do some preprocessing like stripping the
blanks. A possible but not very efficient way would be to go through the
string character by character and copy those that are not blanks into a new
string. Another way would be to consider the remove_if() function with a
predicate that should look like
std::bind2nd(std::equal_to<char>(), ' ')
In order to make lower case comparisons you'll have to modify the condition
of the while loop given above, a little bit. At the moment it compares
character by character taking upper and lower case into account. I guess
this should get you started. Otherwise try and post when you've got some
more trouble.
HTH
Chris