嗨,我尝试创建一个函数,让用户知道输入的单词是否是回文(是拼写反向,例如:皮划艇)。这是我想出的功能,但由于某种原因,函数总是返回false。Bool函数总是返回false
#include <iostream>
#include <cctype>
using namespace std;
bool compare(string str2)
{
int first = 0, mid, last = (str2.size() - 1);
while(first < last)
{
if(first == last)
{
first++;
last--;
}
else return(false);
}
return(true);
}
int main()
{
string pal;
cout <<"Enter your single word palindrome: ";
getline(cin,pal);
if(compare(pal) == true)cout << pal <<" is a palindrome.\n";
else cout << pal <<" is not a palindrome.\n";
return(0);
}
如果(第一==最后一个) - >第一个和最后的索引数字,你需要比较你有你while循环的字符 –
,你如果是错误的。你需要'str2 [first] == str2 [last]'因为你正在检查'first'是否小于'last',并且'first'和last是一样的,这不能同时为真。 –
你的意思是'str2 [first] == str2 [last]'? – Ben