A palindrome is a phrase that reads the same both forward and backward. Write a
ID: 3630170 • Letter: A
Question
A palindrome is a phrase that reads the same both forward and backward. Write a C++ program that reads a line from cin, prints its characters in reverse order on cout, and then pronounces judgement on whether the input line is a palindrome. Use the substr function within a loop to extract and print the characters one by one from the string, starting at the end of the string; at the same time, extract corresponding character starting at the beginning of the sting to compare with it. For example, here are two sample runs of the program:Enter string: able was I ere I saw elba
able was I ere I saw elba
is a palindrome.
Enter string: madam I'm adam
madam I'm adam
is not a palindrome.
Explanation / Answer
please rate - thanks
#include<iostream>
#include<string>
using namespace std;
bool isPalindrome( string& );
int main()
{string input;
bool palin;
int i;
cout<<"Enter a string: ";
getline(cin,input);
palin=isPalindrome(input);
if(palin)
cout<<input<<" is a Palindrome ";
else
cout<<input<<" is not a Palindrome ";
system("pause");
return 0;
}
bool isPalindrome(string& input)
{int i=0;
bool y=false;
string::size_type j=input.length()-1;
while(input.substr(i,1).compare(input.substr(j,1))==0&&i<=j)
{do{
i++;
}while(!isalpha(input[i]));
do
{
j--;
}while(!isalpha(input[j]));
}
if(i>j)
y=true;
return y;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.