简体   繁体   English

函数没有返回预期的输出

[英]function not returning the expected output

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我写了一个简单的函数,它接受一个字符串,然后它反转字符串并检查字符串是否是回文,换句话说,如果字符串是对称的,如果是,则返回 true 否则返回 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";
}
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.这个循环以i == text.size() ,这意味着您在第一次迭代中访问text[text.size()] That is one-past-the-end of the string and therefore always returns '\\0' .这是字符串的最后一个,因此总是返回'\\0'

You add that as first element to rev_text .您将其作为第一个元素添加到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. rbegin()rend()为您提供反向遍历向量的迭代器。

Or even simpler using <algorithm> :或者使用<algorithm>更简单:

auto rev_text = text;
std::reverse(rev_text.begin(), rev_text.end());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM