以下代码是句子回文检查器。我是一名新手程序员,所以调试该代码很困难。显示错误的输出。
例如,如果句子是“一个人,一个计划,一条运河:巴拿马”
结果是假而不是真。 (空格和标点符号应忽略。)
#include <iostream>
class Solution
{
public:
bool isPalindrome(std::string s)
{
int l, i;
i = 0;
l = s.length();
while (i <= (l - 1))
{
if (s[i] == ' ' || ispunct(s[i]) == true)
i++;
else if (s[l - 1] == ' ' || ispunct(s[l - 1]) == true)
l--;
else if (tolower(s[i]) == tolower(s[l - 1]))
{
l--;
i++;
}
else
return false;
}
return true;
}
};
int main(void)
{
Solution s;
const std::string text = "Panama";
std::cout << s.isPalindrome(text);
return 0;
}
最佳答案
问题很可能是character classification functions(例如ispunct
)没有传回bool
结果。
它们返回int
,其值可以是“true”的任何非零值。
这意味着像ispunct(s[i]) == true
这样的条件实际上可能是标点字符的false
。
您需要使用例如改为ispunct(s[i]) != 0
(或只是简单的ispunct(s[i])
)。
关于c++ - 我的句子回文代码(C++)有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63241576/