need help in stack and queue!! please

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
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
able was i ere

(not a palindrome)
Last edited on
Hi, I try remove the comma from the statement, it still can't test Able was I ere, I saw Elba. is a palindrome
you have to remove the comma from your test statement. It should now become
Able was I ere I saw Elba

and not
Able was I ere, I saw Elba
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.
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?
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.
1
2
3
4
5
6
while ( character != '\n' ) {
   if ( character != ','&& character != '.'&& character != ' ' ) {
       // do stuff
   }
   cin.get ( character );
}
Last edited on
Topic archived. No new replies allowed.