Search code examples
c++palindrome

Question about the logic of a simple C++ function (is_palindrome)


The function below is supposed to check if the input parameter is a palindrome and return true/false.

I know that there is a mistake in the code, it's supposed to be: int i = text.size() - 1;

Question: if I don't add "-1" and print out text and textR, both of them would be "madam" and in my understanding when I check (text == textR) it's supposed to be true. It does return false, however.

Could someone please explain what am I missing?

I understand that it has something to do with string.size() and string contents not being the same thing and that a string index starts with a 0... I still don't fully get why text != textR.

#include <iostream>
#include <bits/stdc++.h> 

// Define is_palindrome() here:

bool is_palindrome(std::string text) {

  // create an empty string to store a reversed version of text 
  std::string textR;

// iterating backward over text and adding each character to textR
  for (int i = text.size(); i >= 0; i--) {
    textR.push_back(text[i]);
  }

std::cout << text << std::endl;
std::cout << textR << std::endl;

  // check if the reversed text is the same as text; return true or false

  if (text == textR) {
    return true;
  } else {
    return false;
  }
}

int main() {

  std::cout << is_palindrome("madam") << "\n";

}

Solution

  • text[text.size()] is '\0' (nul character) which is not printable.

    so TextR is "\0madam" instead of expected "madam".