If I type 'ab' or 'abcba', it says that it is palindrome, while it is not. Also if i type 'try', it says it is not palindrome, which is true. Please fix the error.
#include <iostream>
usingnamespace std;
int main() {
// assume we have a palindrome
bool palindrome = true;
string str; //forward string var
string rstr; //backward string var
// input
getline(cin, str);
// copy value
rstr = str;
// reverse value
std::reverse(rstr.begin(), rstr.end(),);
int index = 0;
for (charconst &c: str) {
// compare string with string reversed char by char including spaces.
if (c != rstr[index++]) {
palindrome = false;
}
}
// print out answer
if (palindrome) {
cout << str << " is a palindrome" << endl;
} else {
cout << str << " is not a palindrome" << endl;
}
return 0;
}
I suspect it is something to do with that tricky, difficult-to-read line 14. The second statement in a for declaration specifies a check to perform to decide whether or not to continue the loop. The only check here that matters is the rside > length/2 because it falls on the right side of the comma operator. I think changing the greater-than sign to greater-than-or-equal-to sign may fix your problem, but it is a superfluous check.
To make the code clearer and easier to debug, use the for loop structure to move and evaluate lside. Inside the loop, just calculate rside each time. It will be a lot easier to read the code and see what's going on.