2014-02-27 142 views
0

我剛開始學習C++,我遇到了「const char *'無效轉換爲'char'的問題[在我的源代碼中。「從'const char *'無效轉換爲'char'[-fpermissive]」

const string alphabet = "abcdefghijklmnopqrstuvwxyz"; 
    string gameAlphabet = alphabet; 

    char letterguess; 
    int limbnumber = 0; 

    do 
    { 
     cout << "Please choose a letter: "; 
     cin >> letterguess; 
     cout << letterguess; 

     if (theWord.find(letterguess) == string::npos) 
     { 
      int temp2 = theWord.find(letterguess); 
      theWord[temp2] = letterguess; 
      int temp3 = gameAlphabet.find(letterguess); 
      if (gameAlphabet[temp3] = " ") 
      { 
       cout << "You have already guessed this letter, please try again."; 
      } 
      gameAlphabet[temp3] = " "; 
      cout << gameAlphabet; 
     } 
     else 
     { 
      limbnumber++; 
      int temp1 = gameAlphabet.find(letterguess); 
      gameAlphabet[temp1] = " "; 

      if (limbnumber == 7) 
      { 
       cout << "\n\nSorry " << playername << ", you lose."; 
       cout << "Please try again."; 
      } 

     } 

發生在線路19,23和30。如果你們可以看到我已經犯任何錯誤,讓我知道了「從‘爲const char *’到‘符’[-fpermissive]無效的轉換」 。謝謝!

+0

'gameAlphabet [temp3]'需要一個角色。你不能將多個字符合併成一個。 – chris

+0

'if(gameAlphabet [temp3] =「」)'可能不會做你想做的。 –

回答

1
if (gameAlphabet[temp3] = " ") 
... 
gameAlphabet[temp3] = " "; 
... 
gameAlphabet[temp1] = " "; 

在每一種情況下,你要指定一個指針(因爲" "實際上是const char*)到你的字符串gameAlphabet中的角色。

要解決此問題,請將" "更改爲' ',這是一個空格字符。

此外,我猜if聲明可能應該是比較,這意味着它應該使用比較運算符==。在語句中出現

+0

''「''是一個const char [1]'。 – chris

+0

顯然你是對的。我只是想說明一點,挖掘編譯器錯誤使用的相同術語。 – PaF

2

誤差這樣

gameAlphabet[temp3] = " "; 

" "是一個字符串,在表達式被轉換爲指針字面的第一個字符。而不是字符串文字,你必須使用char類型的對象。例如

gameAlphabet[temp3] = ' '; 

這不是雙引號,而需要使用單引號。雖然你可以用下面的方式寫字符串文字

gameAlphabet[temp3] = " "[0]; 

但是這段代碼只會讓用戶感到困惑。

還要考慮到您的程序無效。例如,讓考慮這個代碼片段

if (theWord.find(letterguess) == string::npos) 
    { 
     int temp2 = theWord.find(letterguess); 
     theWord[temp2] = letterguess; 

條件theWord.find(letterguess) == string::npos meabs的字符沒有被發現,那麼下面的語句

 int temp2 = theWord.find(letterguess); 

回報string::npos你可能不是字符串

在使用這個值作爲指數
 theWord[temp2] = letterguess; 
這個語句後

而且

 int temp3 = gameAlphabet.find(letterguess); 

你必須檢查temp3是否等於string :: npos。否則,代碼具有未定義的行爲。

相關問題