为什么我的cout打印两次

Why does my cout print twice?

本文关键字:两次 我的 cout 打印 为什么      更新时间:2023-10-16

我正在开发一个基于文本的游戏,希望玩家选择单人或多人游戏。我的代码中有以下检查:

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()有时会解决此问题,但到目前为止没有任何效果。

你应该

cin.clear()之后打电话给cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');

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 在这种情况下不能保证做任何有用的事情(它的行为是实现定义的),所以唯一的可移植方法是丢弃字符直到换行