2014-01-11 209 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不能保证做任何有用的事情在这种情况下,(被定义其行为的实现)所以唯一的简单的方法是放弃字符,直到新行