Question: Hi, for my C++ program I need help when it checks the string if it is a palindrome or not. If I put bob it
Hi, for my C++ program I need help when it checks the string if it is a palindrome or not. If I put bob it says that it is a palindrome but if I put a man a plan a canal panama it says that it is not a palindrom but it should display that it is a palindrome. How I can fix that? Thanks.
Code:
Code:
#include
using namespace std;
struct StringRec
{
int strLen;
char theStr[256];
};
// adds one character to the string
void AddChar(StringRec& str, char theCh);
// adds one character to the string
void OutputString(StringRec str);
// outputs the string and the length of the string
bool CheckString(StringRec str);
// returns true if string is a palindrome, false otherwise
int main()
{
StringRec theString;
char theChar;
theString.strLen = 0;
cout << "Enter a string: ";
cin.get(theChar);
while (theChar != ' ')
{
AddChar(theString, theChar);
cin.get(theChar);
}
OutputString(theString);
if (CheckString(theString))
cout << "The string is a palindrome ";
else
cout << "The string is not a palindrome ";
}
// add character one by one in char array and increase strlen by one every time
void AddChar(StringRec& str, char ch)
{
str.theStr[str.strLen] = ch;
str.strLen++;
}
//print element of char array one by one until upto strlen
void OutputString(StringRec str) {
int i;
for (i = 0; i cout << str.theStr[i]; } } //print element of char array one by one until upto strlen // to check string or char array is palindrome or not //compare the first element with last //then second with second last......and so on......example.......abcba // if not follow then break the loop bool CheckString(StringRec str) { int i, f = 0; for (i = 0; i { if (str.theStr[i] != str.theStr[str.strLen - 1 - i]) { f = 1; break; } } if (f == 0) return true; else return false; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
