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