String Palindrome with stack and queue (C ++)

This compiles fine and works well without spaces, but as soon as I put spaces in it, it tells me that it is not a palindrome or does not expire. Any help would be greatly appreciated!

int main( ) { queue<char> q; stack<char> s; string the_string; int mismatches = 0; cout << "Enter a line and I will see if it 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; } 
+4
source share
4 answers

Why is it so complicated?

You can simply do:

 #include <string> #include <algorithm> bool is_palindrome(std::string const& s) { return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin()); } 
+1
source

First line

 cin >> the_string; 

doesn't get the whole line. Use this instead

 getline(cin, the_string); 

Secondly, when debugging your algorithm, print a lot of information. For example, if you add a line

 cout << "You entered: '" << the_string << "'" << endl; 

you can easily see which line you are actually checking.

+1
source

I got this solution to work fine.

 int main( ) { queue<char> q; stack<char> s; string the_string; int mismatches = 0; cout << "Enter a line and I will see if it a palindrome:" << endl; 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; } 
+1
source
 void main() { queue<char> q; stack<char> s; char letter; int mismatches = 0; cout << "Enter a word and I will see if it a palindrome:" << endl; cin >> letter; q.push(letter); s.push(letter); int i = 0; while (cin.peek() != '\n') { cin >> letter; if (isalpha(letter)) { q.push(letter); s.push(letter); } 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; } cout << endl; cout << "Homework done!" << endl; cout << "You are Welcome!" << endl; system("pause"); } 
-1
source

All Articles