2016-03-02 98 views
-2

此代碼嘗試測試字符串是否是迴文。它讀取一串字符,將每個字符讀入堆棧並同時將其添加到隊列中。然後,它使用基本的堆棧和隊列操作來確定字符串是否是迴文。錯誤:在迴文程序中從'char'無效轉換爲'const char *'

該方案與上述錯誤(S),當它擊中炸燬:

inStack.push(inString[i]); 
inQueue.push(inString[i]); 

,我不明白爲什麼,或如何解決它。我已經完成了對這個錯誤的研究,因爲它適用於我的案件並沒有取得豐碩的成果。我對C++相當陌生,所以如果我忽略了一些愚蠢的行爲,請原諒我。

的代碼如下:

#include <iostream> 
#include <stack> 
#include <queue> 
#include <string> 

using namespace std; 

int main() 
{ 
    stack <string> inStack; 
    queue <string> inQueue; 
    string inString; //user input 
    int inLength; //loop counter variable 
    bool isPalindrome(false); 

    cout<<"Enter a word to see if it is a palindrome: "; 
    cin>>inString; 

    if (inString.size() > 0) 
    { 
     for (int i = 0; i <= inLength; i++) 
     { 
      inStack.push(inString[i]); //put string chars onto stack 
      inQueue.push(inString[i]); //add string chars to queue 
     } 

     isPalindrome = true; 

     while (isPalindrome && (!inStack.empty()) && (!inQueue.empty())) 
     { 
      if (inStack.top() != inQueue.front()) 
      { 
       isPalindrome = false; 
      } 
      else 
      { 
       inStack.pop(); 
       inQueue.pop(); 
      } 
     } 
    } 

    if(isPalindrome == false) 
    { 
     cout<<"It is not a palindrome."<<endl; 
    } 
    else 
    { 
     cout<<"It is indeed a palindrome."<<endl; 
    } 

return 0; 
} 
+0

inString [i]是一個字符,而不是一個字符串。如果你想要這樣做,你應該嘗試在inStack中創建一個char向量。另外,您應該發佈完整的編譯器消息,包括行號。 – xaxxon

+0

你不明白你爲什麼不能把'char'轉換成'const char *'?你明白爲什麼''A''永遠不會被轉換爲,例如'0x40000144'?你的容器設置爲你添加'string'元素給他們。也許你打算讓他們接受'char'類型呢? – mah

+0

你的堆棧應該保存字符,而不是字符串。但是,錯誤消息沒有意義。我確定它來自不同的程序。 – SergeyA

回答

1

你的代碼有三個主要的錯誤。

您正在將字符推送到定義爲保存字符串的堆棧和隊列中。字符串構造函數不能隱式地從char轉換爲字符串,因爲沒有構造函數需要char。你可能意味着它們定義爲:

stack<char> inStack; 
queue<char> inQueue; 

您沒有設置inLength;我建議像

之後你的if (inString.size() > 0) {來解決這個問題。

最重要的是,你使用i <= inLength(在for循環條件下),這是行不通的;你應該使用<,因爲push ing inString[inString.size()]實際上是在你輸入的字符之外推一個字符,這總是會導致isPalindrome == false,因爲你的堆棧和隊列在相應的頂部和前部會有一個無效的(隨機垃圾)字符。

這三個更改似乎足以解決您的項目。

一種更簡單的解決方案給你的C++迭代器如何可用於減少必須寫這樣的東西的代碼量的一個示例:

#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

int main() 
{ 
    vector<char> left, right; // left-to-right and right-to-left lists 

    cout<<"Enter a word to see if it is a palindrome: "; 
    string inString; //user input 
    cin>>inString; 

    if(!inString.empty()){ 
     // add characters left to right 
     left.insert(left.end(), inString.begin(), inString.end()); 
     // add characters in reverse order, right to left 
     right.insert(right.end(), inString.rbegin(), inString.rend()); 
     // compare the two vectors 
     if(left == right) 
      cout<<"It is indeed a palindrome."<<endl; 
     else 
      cout<<"It is not a palindrome."<<endl; 
    } 
} 
0

你忘了分配給inLength字符串的實際長度,並獲得外我會非常大,大於它應該是,你可能會得到一個分段錯誤。

嘗試讀取字符串以正確分配值。

inLength = inString.size(); 

我希望這可以幫助你。

相關問題