In: Computer Science
Write a C++ program that reads a string from a text file and determines if the string is a palindrome or not using stacks and queue
Answer:
#include <iostream>
#include <queue>
#include <string>
#include <fstream>
#include<sstream>
using namespace std;
int main (void)
{
string letters;
ifstream f("input.txt"); //taking file as inputstrea
if(f) {
ostringstream ss;
ss << f.rdbuf(); // reading data
letters = ss.str();
}
queue <char> q;
int length;
bool isPalindrome = false;
if (letters.size() > 0)
{
int length = letters.size() / 2;
for (int i=0; i<length; i++)
{
q.push(letters[i]);
}
isPalindrome = true;
for (int i = 1; i <= length && isPalindrome; ++i)
{
isPalindrome = q.front() == letters[letters.size() - i];
q.pop();
}
}
if(!isPalindrome)
{
cout<<"Is not a palindrome."<<endl;
}
else
{
cout<<"Is a palindrome."<<endl;
}
return 0;
}
Output:
Please give thumbsup, or do comment in case of any query. Thanks.