Reputation: 29
I wrote a simple function that accepts a string and then it reverses the string and checks if the string is palindrome, in other words if the string is symmetrical if yes it return true else it returns false
the program runs without any errors but it returns three zeros each one for every time the function is called
#include <iostream>
// Define is_palindrome() here:
bool is_palindrome(std::string text ) {
//std::cout << text << std::endl;
std::string rev_text = ""; // declare a string var to save the reversed word
// reverse the number with a loop
for (int i =text.size(); i >= 0; i--) {
rev_text += text[i];
}
std::cout << text << " " << rev_text << std::endl;
// check if the reversed number is equal to the origianl provided
if (rev_text == text) {
return true;
}
else if ( rev_text != text ) {
return false;
}
}
int main() {
std::cout << is_palindrome("10101") << "\n";
std::cout << is_palindrome("002200") << "\n";
std::cout << is_palindrome("5620265") << "\n";
}
Upvotes: 0
Views: 36
Reputation: 22152
for (int i =text.size(); i >= 0; i--) {
rev_text += text[i];
}
This loop starts with i == text.size()
, meaning that you access text[text.size()]
in the first iteration. That is one-past-the-end of the string and therefore always returns '\0'
.
You add that as first element to rev_text
. So the result contains this extra character that is not in the original.
To fix this, I suggest you use iterators:
for(auto it = text.rbegin(); it != text.rend(); it++) {
rev_text += *it;
}
rbegin()
and rend()
give you iterators that traverse the vector in reverse direction.
Or even simpler using <algorithm>
:
auto rev_text = text;
std::reverse(rev_text.begin(), rev_text.end());
Upvotes: 2