2015-07-22 119 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); 
}