代码
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string str)
{
for(int i = 0; i <= str.length()-1; i++)
{
if(str[i] != str[str.length()-1-i])
{
return false;
}
else
{
return true;
}
}
}
int main()
{
string text;
do
{
cout << "Enter some Text: " << endl;
cin >> text;
if(isPalindrome(text))
{
cout << "The text is a palindrome" << endl;
}
else
{
cout << "The text is not a palindrome" << endl;
}
}while(text != "Q");
return 0;
}
输入_1
otto
输出
The text is a palindrome
输入_2
ottop
输出
The text is a palindrome
输入_3
ottopo
输出3
The text is a palindrome
我想检查用户输入的字符串是否为回文?为什么我的第三个输入的输出出错了?我想我错过了一些东西。
原文由 user5539363 发布,翻译遵循 CC BY-SA 4.0 许可协议
您在循环的第一次迭代中返回 true。你只需要迭代一半的字符串。
更正: