Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ Program Question: Program will accept a string of characters and report whet

ID: 674536 • Letter: C

Question

C++ Program Question:

Program will accept a string of characters and report whether or not that string represents a palindrome. Examples (text in bold is user input):

Palindrome Recognizer:

Enter string : abba

abba is a palindrome.

Enter string : Never odd or even

Never odd or even is a palindrome.

Enter string : accurate

accurate is not a palindrome.

[Note: In all the examples multiple examples shown are for demonstration only, code should ask for one string, report the results, and return to the main menu]

Your tool will read in an entire line of text (not just up to the first space). It will then remove the spaces, punctuation, and normalize the case of the letters (i.e. make them all upper or all lower case). It will then check to see if the resulting string is a palindrome. If so, print out <original string> is a palindrome. If the resulting string is not a palindrome, print out <original string> is not a palindrome.

Explanation / Answer

#include <iostream>
#include <string.h>
#include <ctype.h>

using namespace std;

int main()
{
   string instring;
   cout<<" Enter a string : ";
   getline(cin, instring);   //Takes string input of unknown size
    int len = instring.size();  
    len++;
   const char* pt = instring.c_str(); //Converts it into a constant char string type for function strncpy()
   char* str = new char[len];
   strncpy ( str, pt, len); //Converts the constant string into a character string
  
   int i=0,j=0;
   while (str[i]!='') //Till the end of the string
    {
     if(!isalpha(str[i])) //If the element at current position is other than an alphabet, then we remove it from string here
     {
       for(j=i+1;str[j]!='';j++)
          str[j-1]=str[j];
  
       str[j-1]='';
       i--;
   }
   str[i]=tolower(str[i]); //Converting each alphabet to lower case letter
     i++;
    }
    len=0;
    for(i=0;str[i]!='';i++,len++); //Calculate length of the string obtained after removing whitespaces and other characters(other than alphabets)
    int flag=0;
   for(i=0,j=len-1;i<len/2;i++,j--) //Checking if the string is palindrome or not by comparing the corresponding alphabets from starting and end of the string
    {
      if(str[i]!=str[j])
      {
       flag=1;
       break;
      }  
   }
   if(!flag)
   cout<<instring<<" is a palindrome!";
   else
   cout<<instring<<" is not a palindrome!";

   return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote