Palindrome program

The instructions for the program is

bool isPalindrome = true;

queue<char> Q;
stack<char> S;
string str;
cout<< "Enter a word : ";
getline(cin, str, '\n');

2. enqueue the string into the queue

3. push the string into the stack

4. while the stack is not empty and the queue is not empty do the followings:

if the front of the queue is not equal to the top of the stack:
dequeue the queue;
pop the stack;
isPalindrome=false;
else
dequeue the queue;
pop the stack;
5. if (isPalindrome)
cout << str << " is a palindrome" << endl;
else
cout << str << " is not a palindrome " << endl;

I believe the program does that but only checks the first and last letters, how do I get it to check the rest and accurately say it is or isn't a Palindrome.

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
46
47
48
49
50
51
52
53
54
55
56
#include <queue>
#include <stack>
#include <string>
#include <iostream>


using namespace std;

int main()
{
	string str;
	int i;
	queue<char> Q;
	stack<char> S;
	bool isPalindrome = true;

	cout <<"Enter a text in lowercase: "<< endl;
	getline(cin, str);
	
	for (i = 0; i < str.length(); i++) {
			str[i]= str.at(i);
	}
	
	for (i = 0; i < str.length(); i++) {
		Q.push(str[i]);
		S.push(str[i]);
	}

	for (i = 0; i < str.length(); i++) {
	
	if (Q.front() != S.top())
	{
		Q.pop();
		S.pop();
		isPalindrome=false;
	}
	else{
		Q.pop();
		S.pop();
		
	}


	if(!isPalindrome) {
			cout << str <<"  is not a palindrome."<<endl;
			break;
	}
	else{
		cout << str <<"  is a palindrome. " << endl;
			break;
		}
	}
	
	system("pause");
	return 0;
}


Last edited on
You left out this part:
4. while the stack is not empty and the queue is not empty do the followings:

So you need to put a while loop around your if (Q.front() != S.top()) { /* ... */ } else { /* ... */ } statements.

Also:
20
21
22
for (i = 0; i < str.length(); i++) {
    str[i]= str.at(i);
}

Not sure what you're trying to do here, because this code doesn't do anything.
(It assigns each character in the string to itself.)

Also, as another suggestion, in this code:
31
32
33
34
35
36
37
38
39
40
41
if (Q.front() != S.top())
{
	Q.pop();
	S.pop();
	isPalindrome=false;
}
else{
	Q.pop();
	S.pop();
	
}

Since you're popping Q and S regardless of whether the condition is true or false, you can just write those outside of the if statements:
31
32
33
34
35
36
if (Q.front() != S.top())
{
    isPalindrome = false;
}
Q.pop();
S.pop();
Thanks, the while loop and a few tweaks got it working. I had tried many different things to get this working and the code you identified was left over from that so I removed it. Thanks again!!!
Topic archived. No new replies allowed.