2014-01-11 270 views
0

我正在研究基於文本的遊戲,並希望玩家選擇單人遊戲或多人遊戲。我在我的代碼如下檢查:爲什麼我的cout打印兩次?

cout << "Welcome to Hangman!\nIs this a [s]ingle or [m]ultiplayer game?\nGame mode: "; 

int type = cin.get(); 
cin.clear(); 

//While input isn't single character s or m (either case) 
while (type != 115 && type != 109 && type != 83 && type != 77) { 
    cout << endl << "Please try again.\nGame mode: "; 
    cin.clear(); 
    type = cin.get(); 
} 

發生了什麼事是,如果玩家提供了一個無效的輸入「請稍後再試遊戲模式:」打印了兩次,但如果玩家只需點擊進入它打印一次。我是C++的初學者,閱讀cin.clear()有時可以解決這個問題,但目前爲止沒有任何工作。

+0

'type'可能是新行字符()每隔一次。 – Dialecticus

+2

'cin.clear()'只會清除錯誤標誌。在流中按回車仍然有'\ n'。 – dyp

+1

另外,爲什麼你不使用字符文字來比較類型?例如。 'type =='s'' – dyp

回答

0

你應該叫cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');cin.clear()

cout << "Welcome to Hangman!\nIs this a [s]ingle or [m]ultiplayer game?\nGame mode: "; 

int type = cin.get(); 
cin.clear(); 

//While input isn't single character s or m (either case) 
while (type != 115 && type != 109 && type != 83 && type != 77) { 
    cout << endl << "Please try again.\nGame mode: "; 
    cin.clear(); 
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    type = cin.get(); 
} 

編輯:作爲DYP在評論中提到sync不能保證做任何有用的事情在這種情況下,(被定義其行爲的實現)所以唯一的簡單的方法是放棄字符,直到新行