Search code examples
c++palindrome

C++ cin.ignore To ignore spaces, numbers, and characters to test a palindrome


I need to process a user input to see if it is a palindrome. Our professor said to use cin.ignore() to ignore spaces, numbers, and other characters so we will just compare the letter inputs.

So far I have just found code that ignores just one of these at a time and the code is more advanced than my learning so I do not know how to modify or apply it to my code.

I have the code to check the palindrome, I just do not know how to make it ignore the unwanted inputs.

Sorry this sort of question has been asked many times over but I cannot seem to figure it out.

Thanks in advance.

do
{
    checkInput = false;

    cout << "Enter the Palindrome: ";
    getline(cin, input);

    len = input.length();

    if (len == 0)
    {
        cout << "\nNo data was entered, please enter a palindrome.\n";
        checkInput = false;
    }

} while (checkInput);

for (int i = 0, j = input.size() - 1; i < input.size(); i++, j--)
{

    if (input[i] != input[j] && input[i] + 32 != input[j] && input[i] - 32 != input[j])
    {

        isPalindrome = false;
        break;

    }
}

if (isPalindrome)
{
    cout << "This is a Palindrome!!" << endl;
}

else
{
    cout << "This is not a Palindrome." << endl;
}

Solution

  • im assuming that input is a string. if so then what we want to do before your for loop is have another for loop to run through the string and remove anything unwanted from the string. I am going to assume that all you want to deal with are the upper and lowercase letters, as we are focusing on the ascii values between 65-90 and 97-122. source http://www.ascii-code.com/

    to so do we can simply check each index in the string to see if it falls between these two ranges, and if it doesn't, then delete it.

        for(unsigned int i = 0; i<input.size();i++)
        {
          if(input[i]< 65 || (90 <input[i] && input[i] < 97) || input[i] > 122)   
          {
            input.erase(i,1);
            i--
          }
        }
    

    that should work.