2015-07-22 172 views
-1

嗨,我尝试创建一个函数,让用户知道输入的单词是否是回文(是拼写反向,例如:皮划艇)。这是我想出的功能,但由于某种原因,函数总是返回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); 
} 
+2

如果(第一==最后一个) - >第一个和最后的索引数字,你需要比较你有你while循环的字符 –

+0

,你如果是错误的。你需要'str2 [first] == str2 [last]'因为你正在检查'first'是否小于'last',并且'first'和last是一样的,这不能同时为真。 –

+2

你的意思是'str2 [first] == str2 [last]'? – Ben

回答

2

你实际上并没有做任何的字符比较,只是比较指标firstlast - 他们不匹配,所以你返回false。

0

if(first == last){} 这是错误。

1

继代码下面,如果我们假设last是大于0,while(first < last)后跟if(first == last)false,因此该函数返回falsetrue。我猜你可能想要比较字符而不是索引。

int first = 0, mid, last = (str2.size() - 1); 

while(first < last) 
{ 
    if(first == last) 
    { 
     first++; 
     last--; 
    } 
    else return(false); 
} 
0

在你的代码,你应该比较charint。所以,试试这个:

bool compare(string str2) 
{ 
    int first = 0, mid, last = (str2.size() - 1); 

    while(first] < last) 
    { 
     if(str2[first] == str2[last]) 
     { 
      first++; 
      last--; 
     } 
     else 
      return(false); 
    } 
    return(true); 
}