Thursday, July 9, 2009

Palindrome program in c++.?

help writing this palindrome program for my c++ class.


HERE WHAT THE CODE SHOULD BE LIKE.


Write a program that takes a line of input from the keyboard and check to see if that line is a palindrome. Your program should ignore blanks, punctuation, and lettercase





Your program should output what the user entered as well as the reversed line.





Sample output:





Please enter a phrase, and I will tell you if it is a palindrome.


%26gt;%26gt; Madam I'm Adam


You entered Madam I'm Adam


True. This IS a palindrome, the reversed string is madamimadam


Would you like to enter another phrase (y/n)


%26gt;%26gt; y


Please enter a phrase, and I will tell you if it is a palindrome.


%26gt;%26gt; Kayak


You entered Kayak


True. This IS a palindrome, the reversed string is kayak


Would you like to enter another phrase (y/n)


%26gt;%26gt; y


Please enter a phrase, and I will tell you if it is a palindrome.


%26gt;%26gt; Last Stall


You entered Last Stall


False. This is NOT a palindrome, the reversed string is llatstsal.





Thanks in Advance :)

Palindrome program in c++.?
Hi,


sounds like an homework or an interview question :D, anyway you can use this :) :





string Test;


cin %26gt;%26gt; Test;


bool bFlag = true;





string::iterator IterFw = Test.begin();


string::reverse_iterator IterBw = Test.rbegin();


while( *(IterFw++) == *(IterBw++) %26amp;%26amp; IterFw != Test.end() ) {


bFlag = false;


}





if( !bFlag )


cout %26lt;%26lt; "it's a palindrome" %26lt;%26lt; endl;


else


cout %26lt;%26lt; "it's NOT a palindrome" %26lt;%26lt; endl;
Reply:string Test;


cin %26gt;%26gt; Test;


bool isPalidrom = false;


char data[256];





strcpy(data, Test.c_str());


strlwr(data);


Test = data;


string::iterator IterFw = Test.begin();


string::reverse_iterator IterRev = Test.rbegin();


while(IterFw != Test.end() %26amp;%26amp; isPalidrom) {


if (!isspace(*IterFw) %26amp;%26amp; !ispunct(*IterFw) %26amp;%26amp; !isspace(*IterRev) %26amp;%26amp; !isspace(*IterRev))


{


if (*IterFw != *IterRev)


{


isPalidrom = false;


}


else


{


++IterFw;


++IterRev;


}


} // If not space or punctation


else if (isspace(*IterFw) || ispunct(*IterFw))


{


++IterFw;


}


else


{


++IterRev;


}


}





if( isPalidrom )


cout %26lt;%26lt; "it's a palindrome" %26lt;%26lt; endl;


else


cout %26lt;%26lt; "it's NOT a palindrome" %26lt;%26lt; endl;


No comments:

Post a Comment