Suds2
Suds2

Reputation: 261

Having trouble with simple palindrome program

I'm trying to code a simple c++ program that lets the user know if the word they input is palindrome or not. Example: 'mom' is palindrome.

Here's what I have:

#include <iostream>
#include <string>

using namespace std;

// Forward Declaration
string reversed_string(string);


int main(){
    string str;
    string reversed;
    cout << "Enter string to check:\n";
    getline(cin, str);

    reversed = reversed_string(str);

    if(str == reversed){
        cout << str << " is palindrome\n\n";
    }
    else{
        cout << "Not palindrome";
    }
}

string reversed_string(string str){
    string reversed;

    for(int i = int(str.length()); i >= 0; i--){
        reversed += str[i];
    }
    return reversed;
}

When I try to input a palindrome word, it always goes to the else statement in my main function. What am I doing wrong?

Upvotes: 0

Views: 117

Answers (1)

paxdiablo
paxdiablo

Reputation: 881113

The last character of a string is at index len - 1, not len. As per the standard (C++11):

Returns *(begin() + pos) if pos < size(). Otherwise, returns a reference to an object of type charT with value charT(), where modifying the object leads to undefined behavior.

What that standardese actually means is that, if pos is not less than the string length, the function returns a reference to a null character. Hence the first character you're putting into your reversed string is the null.

However, you don't really need to reverse the string to find if it's a palindrome, it might be easier to simply use the following (pseudo-code) algorithm:

def isPalindrome(string):
    set left to zero
    set right to one less than string length
    while left is less than right:
        if string[left] is not equal to string[right]:
            return false
        add one to left
        subtract one from right
    return true

Given you have to process every character to form the reversed string anyway, you may as well use that processing power to just check the characters in the original string. That way, you can exit early if it's not a palindrome.

This will, of course, consider an empty string to be a palindrome, which is arguably correct. If you don't think that's correct, simply put a check in up front:

def isPalindrome(string):
    if string length is zero:
        return false
    set left to zero
    ... and so on

Upvotes: 1

Related Questions