2013-10-16 77 views
0

已修復。謝謝。根據布爾值無法結束do/while循環 - C++

在我的代碼下面,它編譯並運行,但卡在do/while循環中。返回值正在工作,但while循環一定不能識別它,它會無限期地運行。我可以收到真假的回報;都不停止循環。真的迷失在這裏,找不到答案。謝謝。

//helper function for inputGuess 
//checks if the user's guess is in the lowercase alphabet and that 
// it has not been guessed before 
bool Hangman::validGuess() { 
    //checks if the character guess is in the lowercase alphabet 
    if (guess >= 97 && guess <= 122) { 
    //checks if the user's guess has been guessed previously 
    if (guessed.size() > 0) { 
     for (int i = 0; i < guessed.size(); i++) { 
     cout << "enter for\n"; 
     cout << "guess[i]: " << guessed[i] << endl; 
     if (guess != guessed[i]) { 
      cout << "1st true: guess has not been guessed\n"; 
      return true; 
     } 
     else { 
      cout << "1st false: same letter\n"; 
      return false; 
     } 
     } 
    } 
    else { 
     cout << "2nd true: guessed size is 0\n"; 
     return true; 
    } 
    } 
    else { 
    cout << "2nd false: not alphabet\n"; 
    return false; 
    } 
} 

//gets input for guess, checks if guess is valid, adds guess to guessed 
void Hangman::inputGuess() { 
    bool valid = false; 
    do { 
    cout << "Please enter your guess: "; 
    cin >> guess; 
    cout << endl; 
    valid = validGuess(); 
    cout << "valid: " << valid << endl; 
    } while (valid == false); 
    guessed.push_back(guess); 
} 
+0

你不能總是假設你正在運行的系統使用ASCII。即使你這樣做,「a」也比97更清晰。請記住,還有一個「islower」函數。 – chris

+0

我認爲你所顯示的代碼本身並不是問題,但它也不完整。我會認爲還有另一個外部循環,並且你被困在這個外部循環中。請添加其餘代碼(如果它不太多)。 –

+0

你的代碼不能編譯('guess'沒有在'validGuess()'中聲明),所以你是如何設法讓它運行的? – Walter

回答

0

guessed爲空時,您有一個未定義的返回事件,因爲它已經過去並且沒有默認返回。

無論如何,這段代碼看起來過於複雜。像這樣的東西可能會更好:

bool HangMan::validGuess() { 
    //checks if the character guess is in the lowercase alphabet 
    if (isalpha(guess)) { 
     //checks if the user's guess has been guessed previously 
     if (find(guessed.begin(), guessed.end(), guess) != guessed.end()) { 
      cout << "1st false: same letter\n"; 
      return false; 
     } 
     else { 
      cout << "1st true: guess has not been guessed\n"; 
      return true; 
     } 
    } else { 
     cout << "2nd false: not alphabet\n"; 
     return false; 
    } 
} 
1

你應該將guess作爲參數傳遞給validGuess()這就是你的問題。嘗試加入

this->guess 

而不是隻是猜測。

+0

它看起來像一個全局變量,因爲它也沒有在'inputGuess()'中定義。 –

+0

@Daniel:我猜想是一個班級成員,但是我同意它的範圍比任何一個功能都大,這個「答案」可能是一種風格上的改進,但不會解決問題。 –

+0

是的,我明白了。仍然。他「應該」通過它。我們需要看看其餘的類,也許這是一個實例問題,就像函數是靜態的等等。如果它是一個類var,嘗試添加範圍分辨率 – AwokeKnowing