May 31, 2013 at 6:35am UTC
Hi,I am a c++ beginner.
I am using vs,and I got a problem in my code which check a sentence whether a palindrome or not.
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
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
int main ()
{
bool palindrome = true ;
char character;
StackType stack;
Queue queue;
char stackChar;
char queChar;
cout << "Enter a string; press return." << endl;
cin.get(character);
while ( character != '\n' && character != ',' && character != '.' && character != ' ' )
{
if ( isalpha (character))
{
character = tolower(character);
}
stack.Push ( character );
queue. enqueue ( character );
cin.get ( character );
}
while ( palindrome && !queue.isEmpty () )
{
stackChar = stack.Top ();
stack.Pop ();
queue.dequeue ( queChar );
if ( stackChar != queChar )
palindrome = false ;
}
if ( palindrome )
cout << "String is a palindrome." << endl;
else
cout << "String is not a palindrome." << endl;
return 0;
}
Enter a string;press return.
Eve
String is a palindrome.
Enter a string;press return.
Eve,eve.
String is a palindrome.
It seems ok, but when I test this:
Enter a string;press return.
Able was I ere, I saw Elba.
String is not a palindrome.
but "Able was I ere, I saw Elba." in the assignment example is a palindrome.
can anyone tell me whats wrong with my code? please.
Last edited on May 31, 2013 at 6:37am UTC
May 31, 2013 at 6:50am UTC
remove the comma from the statement and then test.
EDIT: your while loop does not check for more characters if it encounters a comma. which means your program only evaluates the string
(not a palindrome)
Last edited on May 31, 2013 at 6:52am UTC
May 31, 2013 at 6:58am UTC
Hi, I try remove the comma from the statement, it still can't test Able was I ere, I saw Elba. is a palindrome
May 31, 2013 at 7:42am UTC
oh. I see. But my assignment is check a sentence, which contain comma and period in the sentence. Even my second tese "Eve,eve." works. So i think is not the test statement wrong. something wrong in the code.
May 31, 2013 at 7:43am UTC
Line 18. You stop processing input when the first word ends. Shouldn't you rather read the whole sentence and merely ignore the insignificant characters?
May 31, 2013 at 7:56am UTC
Hi, Keskiverto,
yes. I have though that too. I knew i should read the whole sentence first and ignore the ',' and '.' store to the stack, and queue, just dont know how.
May 31, 2013 at 7:59am UTC
1 2 3 4 5 6
while ( character != '\n' ) {
if ( character != ',' && character != '.' && character != ' ' ) {
// do stuff
}
cin.get ( character );
}
Last edited on May 31, 2013 at 8:00am UTC