Reputation: 3
Any idea why this doesn't work...i tried level as an input string and it says it's not a palindrome when it is...
I am sure both str and reverse are exactly the same, Can someone point me to where
b. Write a program that reads a word from the user and announces to the user if it is a
palindrome or not.
Your program should interact with the user exactly as it shows in the following example:
Please enter a word: level
level is a palindrome
#include <iostream>
#include <cstring>
using namespace std;
//Function prototypes
bool isPalindrome(string str);
//Variables
string str; // to store our string
int main () {
cout<<"Please enter a word: ";
cin>> str;
isPalindrome(str);
return 0;
}
//Function definition
bool isPalindrome(string str) {
string reverse;
for(int i = str.length(); i >= 0; i--) {
reverse += str[i];
}
cout<<str<<" "<<reverse<<endl;
if (str == reverse) {
cout << str << " is a palindrome";
return true;
}
else {
cout << str << " is not a palindrome";
return false;
}
}
Upvotes: 0
Views: 67
Reputation: 116
Your strings are not of the same length. Check this for yourself using str.length() and reverse.length(). The issue is that your for loop that iterates through str starts at too high a number. str.length is 3 but str[3] is the forth spot in the string str. You need to start at str.lentgh - 1 since array/string indexes start as 0 rather than 1. Get used to the length - 1 expression because is used frequently when iterating through arrays, strings, etc.
Upvotes: 1