I have written code that checks to see if a string is a palindrome. In order to do this I've created two functions: The first turns capital letters into lowercase letters and replaces punctuation with ' '. The second simply checks to see if the cleaned up string is a palindrome.
The two problems I am having are as follows:
1) If my string ends in a punctuation mark my program suggests that known palindromes are not palindromes.
2) I randomly put in "madam my name is adam" and my program suggests that that phrase IS a palindrome. It, of course, is not.
My thoughts are that #1 has to do with the fact that my palindrome compares the 0th (first?) character in the string with the last character in the string and finds that the first character is a character while the last character is actually a space. #2 baffles me, it implies, perhaps, that my checker is stopping at the white space that precedes 'adam'?
#include <iostream>
#include <string>
usingnamespace std;
// function prototypes
string cleanUp(string& phrase);
bool isPalin(string cleanedPhrase);
int main() {
// variable declaration
string userPhrase;
cout << "Please enter your word/phrase: " ;
getline (std::cin, userPhrase);
isPalin(cleanUp(userPhrase));
if (isPalin(cleanUp(userPhrase))) {
cout << "is palin";
}
else
cout << "no";
getchar();
return 0;
}
string cleanUp(string& phrase) {
for (int i = 0; i < phrase.length(); i++)
{
if (isupper(phrase[i]))
{
phrase[i]=tolower(phrase[i]) ;
}
if (ispunct(phrase[i]))
{
phrase[i]=' '; // i think this is where a problem is
}
}
return phrase;
}
bool isPalin(string cleanedPhrase) {
for( int i = 0; i < cleanedPhrase.length() / 2 ; i++) {
if( cleanedPhrase[i] != cleanedPhrase[cleanedPhrase.length()-1-i]) // could be a problem with this procedure as well
returnfalse;
returntrue;
}
}
Are you saying that if i delete the if loop, but keep line 35 I will get the same effect? IE there is no reason to distinguish between caps and lowercase because 35, when applied to any ith character, gives the same result?
The line swap resolved the issue I had with 2. What was I telling the program to do before swapping though? I see that if our for loop finishes and hasn't returned false, then we exit the for loop and return true. What was happening previously though, and why did it only give a false positive sometimes?
switching to phrase erase didn't resolve issue 1. I am guessing that is because I need to remove all the spaces as you suggested?
@acemanhattan
I am saying that the function checks if they are lower or not already.
If they are uppercase it will make it lowercase if it is not upper case
the function does nothing.
On that link I sent you at the very top it says:
cplusplus website link wrote:
tolower
int tolower ( int c );
Convert uppercase letter to lowercase
Converts c to its lowercase equivalent if c is an uppercase letter and has a lowercase equivalent. If no such conversion is possible, the value returned is c unchanged.