FAQ: Code Challenge: C++ Functions - Palindrome

If you compare the length of text and reverse, you will see that reverse has one extra character, even though the two strings seemingly appear to be the same.

In your snippet posted above, reverse doesn’t end up being " madam". Instead of a blank space, a null character (denoted by '\0') has ended up being the first character of your reverse string. So, reverse is actually "\0madam" which appears as "madam" on your screen. On screen, the text and reverse strings will appear indistinguishable, but if you check their length, you will see that the length of text is 5 while that of reverse is 6.
(You can also confirm this by a statement such as std::cout << (reverse[0] == '\0') << "\n" which will output 1 if true and 0 if false)

If you edit the loop initialization to int i = text.size() + 1; or some other out of range index number, you will see undefined behavior (your output could be gibberish or some other unpredictable behavior). Many languages (like Python) will throw an error. But in C/C++, the onus is on the programmer to respect the range/bounds.

My code is pretty much the exact same but the output is still just zeros.
Please help, I’m not sure why this isn’t working.

#include <iostream> #include <string> // Define is_palindrome() here: bool is_palindrome(std::string text) { std::string reverse; for (int i = text.length(); i >= 0; i--) { reverse.push_back(text[i]); } return (text == reverse); } int main() { std::cout << is_palindrome("madam") << "\n"; std::cout << is_palindrome("ada") << "\n"; std::cout << is_palindrome("lovelace") << "\n"; }

Have a look at the loop variable initialization in your for loop.
From earlier in the thread (same logic applies to .size() and .length() ):

Same here, but I think the experience of making programs frequently will help us understand this exercise, I will finish it with the solution they provide, then I will try to make it on my own IDE.

Why int i = text.size() - 1 instead of int i = text.size()
Thank you

The index of the last character in text would be text.size() - 1