String Palindrome with stack and queue

This compiles fine and works well with no spaces, but once I put spaces in it either tells me its not a palindrome or times out. Any help would be greatly appreciated!

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
#include <cassert>    // Provides assert
#include <cctype>     // Provides isalpha, toupper
#include <cstdlib>    // Provides EXIT_SUCCESS
#include <iostream>   // Provides cout, cin, peek
#include <queue>      // Provides the queue template class
#include <stack>      // Provides the stack template class
#include <string>     // Provides string
using namespace std;

int main( )
{
    queue<char> q;
    stack<char> s;
    string the_string;
    int mismatches = 0;
    cout << "Enter a line and I will see if it's a palindrome:" << endl;
    cin  >> the_string;

	int i = 0;
	while (cin.peek() != '\n')
	{
	    cin >> the_string[i];
	    if (isalpha(the_string[i]))
	    {
	       q.push(toupper(the_string[i]));
	       s.push(toupper(the_string[i]));
	    }
	    i++;
    }

	while ((!q.empty()) && (!s.empty()))
	{
		if (q.front() != s.top())
		   ++mismatches;
		q.pop();
        s.pop();
    }

	if (mismatches == 0)
	   cout << "This is a palindrome" << endl;
	else
	   cout << "This is not a palindrome" << endl;

    system("pause");
    return EXIT_SUCCESS;
}
Maybe you should get rid of line 17, since you don't process what you extract from the input stream there. You're also accessing outside the bounds of the_string -- there is no effort made to make sure i doesn't equal or exceed the_string.length().

Consider using getline.
1
2
3
4
5
getline(std::cin, the_string);

	int i = 0;
	while (i < the_string.length())
	{


also, dont do "toupper" because you want to compare the string as it is.
Topic archived. No new replies allowed.