bgsbnny
bgsbnny

Reputation: 21

C++ indicate Palindrome

I'm pretty new to coding in C++ and need your help. In the code below I want to check for Parlindrome and show the reversed text. So if I run this code, it displays the right reversed words, but dont return them true if checked for parlindrome.

The console shows: madam0 ada0 ecalevol0

Why the return is always 0?

Thanks for your help!

#include <iostream>

// Define is_palindrome() here:

bool is_palindrome(std::string text) {
  std::string text_reversed;

  for(int i = text.length(); i >= 0; i-- ) {
    text_reversed += text[i];
    std::cout << text[i];
  }

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

int main() {
  
  std::cout << is_palindrome("madam") << "\n";
  std::cout << is_palindrome("ada") << "\n";
  std::cout << is_palindrome("lovelace") << "\n";
}

Upvotes: 1

Views: 85

Answers (3)

Asteroids With Wings
Asteroids With Wings

Reputation: 17464

Your i starts at text.length(), not text.length() - 1.

So, your first text[i] is a null byte (yes, even for std::string, this is guaranteed).

Thus the first character of text_reversed is a "hidden" character that was not present in text, and the two will never match.

Upvotes: 1

Vasconcelos
Vasconcelos

Reputation: 310

Your biggest problems there are i>=0 and text[i]. It should be i>0 and text[i-1].

And please simplify that return statement.

#include <iostream>

bool is_palindrome(std::string text) {

  std::string text_reversed = "";

  for(int i = text.length(); i > 0; i-- ) {
    text_reversed += text[i-1];
  }
  std::cout << text_reversed <<std::endl;
  std::cout << text <<std::endl;

  return text == text_reversed;
}

int main() {
  std::cout << is_palindrome("madam") << std::endl;
  std::cout << std::endl;
  std::cout << is_palindrome("ada") << std::endl;
  std::cout << std::endl;
  std::cout << is_palindrome("lovelace") << std::endl;
  std::cout << std::endl;
}

Upvotes: 0

Marek R
Marek R

Reputation: 38102

std::string reversed_string(const std::string& s)
{
    return {s.rbegin(), s.rend()};
}

bool is_palindrome(const std::string& s)
{
    return std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin());
}

Documentation of std::equal has example of is_palindrome

Upvotes: 0

Related Questions