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()有時可以解決這個問題,但目前爲止沒有任何工作。
'type'可能是新行字符()每隔一次。 –
Dialecticus
'cin.clear()'只會清除錯誤標誌。在流中按回車仍然有'\ n'。 – dyp
另外,爲什麼你不使用字符文字來比較類型?例如。 'type =='s'' – dyp