I finished a program where it takes lines from a text file and tells you if it is a palindrome or not. While it does tell you if deed or maam is a palindrome,race car and words with spaces or question marks at the end don't satisfy the program even though it is a palindrome. Can anyone tell me how to make the program skip over the special characters like !,? etc and ignore the spaces but still keep the normal format when it prints?
#include <string>
#include <stack>
#include <queue>
#include <iostream>
#include <list>
#include <fstream>
usingnamespace std;
void tokenize(string &X, string separators, list<string> &words)
{ // extracts tokens from x and puts them in list
int length = X.length();
int first = X.find_first_not_of(separators,0);
while (first>=0 && first<length)
{
int last = X.find_first_of(separators,first);
if( last<0 || last > length) last = length;
words.push_back(X.substr(first,last-first));
first = X.find_first_not_of(separators,last+1);
}
}
bool palinstring(string &line) // returns true if line contains palindrome
{
stack<string> S;
queue<string> Q;
list<string> the_words;
string one, two;
tokenize(line," ,;:",the_words);
list<string>::iterator start=the_words.begin();
list<string>::iterator stop=the_words.end();
while (start != stop)
{
S.push(*start);
Q.push(*start);
start++;
}
while (!Q.empty()) // checks to see if we have a palindrome
{
one = S.top(); S.pop();
two = Q.front();Q.pop();
if(one!=two) returnfalse;
}
returntrue;
}
int main()
{
string line;
ifstream pal ("pal.txt");
while (getline(pal,line))
{
cout << line << " <= is " ;
if (!palinstring(line)) cout << "not ";
cout << "a palindrome\n";
}
system("pause");
return 0;
}
here is the output
Was it a car or a cat I saw? <= is not a palindrome
abcdefedcab <= is a palindrome
Niagara, O roar again <= is not a palindrome
Able was I ere I saw Elba <= is not a palindrome
radar <= is a palindrome
tenet <= is a palindrome
refer <= is a palindrome
deeded <= is a palindrome
no lemons, no melon <= is not a palindrome
notion <= is a palindrome
Otto <= is a palindrome
Emma <= is a palindrome
Anna <= is a palindrome
level <= is a palindrome
Madam, I'm Adam <= is not a palindrome
palindrome <= is a palindrome
racecar <= is a palindrome
salads <= is a palindrome
No, it is opposition <= is not a palindrome
read, dear <= is not a palindrome
Poor Dan is in a droop <= is not a palindrome
dented <= is a palindrome
deed <= is a palindrome
Press any key to continue . . .