2017-07-20 40 views
-3

首先,我非常感謝您願意提供的任何幫助。我是C++的新手,並且一直在瀏覽本網站以及解決我的問題的其他資源。確定用戶輸入是否使用C++迴文

此外,這確實是家庭作業的一部分。然而,這個任務已經被打開(令人不安的是,沒有得到這個代碼的工作)。能夠解釋我的特定代碼中的問題以及如何解決我當前的代碼,而不是用剛剛重寫的代碼以不同的方式解決問題,這將是非常好的。我當然在這個美妙的網站上找到了很多方法來解決這個問題!

我沒有得到我的代碼錯誤,但反轉輸出不顯示反轉字符數組。這導致我的小程序,在這裏總是顯示「您的字符串不是迴文!:(」無論輸入是什麼。

#include <iostream> 
#include <string> 

using namespace std; 

int isPalindrome(char *input, char *input2); 
char reverseString(char *input); 

int main() 
{ 
    char input[50]; 
    char input2[50]; 

    cout << "Please enter a string of characters no larger than 50." << endl; 
    cin.getline(input, 50); 
    reverseString(input); 
    cout << "The reversed string is " << input2 << endl; 
    int result; 
    result = isPalindrome(input, input2); 

    if(result == 0) 
      cout << "Your string is a palindrome!" << endl; 
    else 
      cout << "Your string is not a palindrome! :(" << endl; 
return 0; 
} 

int isPalindrome(char* first, char* second) 
{ 
    if (*first == *second) 
      return 0; 
    else 
      return 1; 
} 

char reverseString(char* input2) 
{ 
    int size = sizeof(input2); 
    for (int i = 0; i < (size/2); i ++) 
      swap(input2[i], input2[size-i-1]); 

return *input2; 
} 

我再次感謝所有幫助您可以提供!我道歉,如果這是一個。簡單的錯誤,我俯瞰,應該已經能夠在其他地方找到

+1

您在使用調試器逐步執行代碼時觀察到了什麼? – user0042

+0

使用'* first == * second',將'first'的第一個字符與'second'的第一個字符進行比較。該表達式等於'first [0] == second [0]'。 –

+2

此外,在指針上執行'sizeof'會給你*指針*的大小,而不是它指向的大小。調試器中的快速切換會很快告訴你。請學習如何使用調試器逐行瀏覽您的代碼以找出類似的事情。 –

回答

0

檢查迴文並不需要這麼多的努力

bool isPalindrome(const char* s) // this function is self-contained. 
{         // the caller does not need to provide 
    size_t n = strlen(s);   // any pre-computed value. 
    if (n == 0) 
     return false; 

    const char* e = s + n - 1; 
    while (s < e) 
     if (*s++ != *e--) 
      return false; 
    return true; 
} 

int main() 
{ 
    char input[50]; 

    cout << "Please enter a string of characters no larger than 50." << endl; 
    cin.getline(input, 50); 

    bool result = isPalindrome(input); 

    cout << "Your string is" 
     << ((result) ? " " : " not ") 
     << "a palindrome!\n"; 

    return (result) ? 1 : 0; 
} 

在你reverseString功能:

char reverseString(char* input2) 
{ 
    int size = sizeof(input2);     // <-- ?? sizeof(char*) != strlen(input2) 
    size_t size = strlen(input2);    // <-- should read. 

    for (int i = 0; i < (size/2); i ++) 
      swap(input2[i], input2[size-i-1]); 

    return *input2;       // what's this? returning first char? why? 
} 
+0

謝謝你的幫助。我將通過您提供的代碼工作並試圖更好地理解它。我現在看到爲什麼傳遞指針不起作用。昨晚深夜....並不多!我仍然需要確定爲什麼每次我嘗試將'char input2'傳遞給該函數時都會給我一個錯誤,而不是我通過'char * input2'。 –

+0

這很簡單。從兩端走過繩子,比較並退出,當有差異時 - 不是迴文 - 或者兩個指針交叉 - 迴文。您的IsPalindrome函數僅比較第一個字節和最後一個字節。 –

相關問題