We are to use cin.get()
in this program, but when I use it, it can't determine whether the inputted string is a palindrome. I have even tried with cin.get(str, 0)
but this reads an error message for me. This is the code I have now. Please help.
//program to for palindrome
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string str) //will return a true or false value
{
int leng = str.length(); //local variable for length
char ch1 = str[0]; //cases if string is 0
char ch2 = str[leng - 1];//cases if string is not 0
if(ch1 != ch2) //base case
{
return false;
}
else
{
if(str.length() <= 1)
{
return true;
}
return isPalindrome(str.substr(1, leng - 2)); //recusive computation
}
}
int main()
{
string str; //declare variable str
cout << "Enter a line that might be a palindrome: "<< endl;
cin.get();
bool pal = isPalindrome(str); //assign pal
if(pal)
{
cout <<"The string is a palindrome." << endl;
}
else
{
cout <<"The string is NOT a palindrome." << endl;
}
return 0;
}
The issue is, when it does work, it only checks for palindrome on the word in the sentence, instead of the whole sentence. I know the solution for this will be ignoring or removing the space and the non-alpha letters, but I still get errors doing that.
this is an output sample:
csh> pal
Enter a line that might be a palindrome:
Go hang a salami, I'm a lasagna hog.
The string is a palindrome.
csh> pal
Enter a line that might be a palindrome:
This is another candidate string.
The string is NOT a palindrome.