I posted a question yesterday and didn\'t receive a response. Luckily I was able
ID: 3546398 • Letter: I
Question
I posted a question yesterday and didn't receive a response. Luckily I was able to figure out the error in my code on my own. Here goes another question: Write a program that uses a function called isPalindrome. The function should check to see if the following strings are palindrome or not. Create a file with the following strings: Madam, abba, 22, 67876, 444244, trymeuemyrt, madam i am adam Create the function isPalindrome and call it from the main program inside a while loop for every string you read. Print out the string and whether it is a palindrome or not.Explanation / Answer
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
bool isPalindrome(string& str)
{
bool is_palin = true;
int k = str.length()-1;
for(int i=0; i<=k/2; i++)
{
if(str[i]!=str[k-1-i])
{
is_palin = false; break;
}
}
if(*str.rbegin()==' ') str.erase(str.length() - 1);
return is_palin;
}
int main()
{
ifstream infile("input.txt");
if(!infile)
{
cout << "unable to open file .so exiting from program. " << endl;
return 0;
}
while(!infile.eof())
{
string str;
getline(infile,str);
if(isPalindrome(str))
cout << str << " is a palindrome " << endl;
else
cout << str << " is not a palindrome " << endl;
}
infile.close();
return 0;
}
// OUTPUT
/*
Madam is not a palindrome
abba is a palindrome
22 is a palindrome
67876 is a palindrome
444244 is not a palindrome
trymeuemyrt is a palindrome
madam i am adam is not a palindrome
*/