2016-10-16 20 views
0

私はpalidromesの再帰関数を記述しようとしています。私はコマンド引数が入力されていないときに文字列をテストするときに正しい答えを得ます。コマンド引数があるとき。それは真実であったとしても偽を返し続けます。私は間違って何をしたのですか?再帰的なパリドローム

#include <iostream> 
#include <string> 
#include <algorithm> 
using namespace std; 

bool palindrome(string word); 
string formatString(string s); 

int main(int argc , char * argv[]) 
{ 
if(argc < 2) 
{ 
string inputString; 
int last = inputString.length()-1; 
cout << "Welcome To My Palidrome Tester!" << endl; 
cout << "Please Enter A String To Test if it is A Palidrome: "; 
getline(cin, inputString); 
//testForPalindrome(inputString); 
string newW = formatString(inputString); 
//cout << "It is a palindrome" ? (palindrome(newW) == true) : "It is Not a palidrome"; 
if(palindrome(newW) == true) 
    cout << "It is a palindrome" << endl; 
    else 
    cout << "It is not palindrome" << endl; 
} 
else 
{ 
string commandStr; 
for(int i = 1; i < argc; i++) 
{ 
    commandStr += argv[i]; 
} 
string newW = formatString(commandStr); 
if(palindrome(newW) == true) 
    cout << "It is a palindrome" << endl; 
    else 
    cout << "It is not palindrome" << endl; 

} 
return 0; 
} 
bool palindrome(string word) 
{ 
int length = word.length(); 

string first = word.substr(0,1); 
string last = word.substr((length - 1), 1); 

if (first == last) 
{ 
    word = word.substr((0 + 1), (length - 2)); 
    if (word.length() <= 1) return true; // Problem line? 
    palindrome(word); 
} 
else 
    return false; 
} 
string formatString(string s) 
{ 
string p; 
size_t position = s.find(' ', 0); 
while(position != string::npos) 
{ 
    s.erase(position,1); 
    size_t newPosition = position+1; 
    position = s.find(' ', newPosition); 
} 
for(int i = 0; i < s.size(); i++) 
{ 
    if(ispunct(s[i])) 
    { 
     s.erase(i,1); 
    } 
    if(isupper(s[i])) 
    { 
     s = tolower(s[i]); 
    } 
} 
return s; 
} 
+0

このような問題を解決する適切なツールは、デバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。最低限、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、その問題を再現するためのデバッガ。 –

答えて

1
string inputString; 
int last = inputString.length()-1; 

あなたもすぐに文字列の長さを取っています。

に変更
string inputString; 
cout << "Please Enter A String To Test if it is A Palidrome: "; 
getline(cin, inputString); 
formatString(inputString); 
int last = inputString.length() - 1; 
if (recursionPalindrome(inputString, 0, last) != 0) 
    cout << "It is a Palindrome" << endl; 
else 
    cout << "It is not a palindrome" << endl; 
+0

ありがとうございます –

1

それはそれはrecursionPalindromeロジックから「ではない回文」をする必要がありながら、「回文」の印刷とfalseを返すようですか?

if(recursionPalindrome(inputString,0,last) == 0) 
    cout << "It is a Palindrome" << endl; 
else 
    cout << "It is not a palindrome" << endl; 
+0

申し訳ありません "abcba"のようなPalindrome文字列のために –

+0

を指定できますか?recursionPalindrome関数からtrueを返しますが、0と比較した後にfalseを返します。これは "palindrome" – linpingta

+0

Ohh私は理解している –