为什么我的cout打印两次?

时间:2014-01-11 14:50:16

标签: c++

我正在制作一款基于文字的游戏,希望玩家选择单人或多人游戏。我的代码中有以下检查:

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()有时会解决这个问题,但到目前为止还没有任何工作。

1 个答案:

答案 0 :(得分: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();
}

编辑:由于评论sync中提到的dyp不能保证在这种情况下做任何有用的事情(它的行为是实现定义的)所以唯一可移植的方法是丢弃字符直到新行

相关问题