简体   繁体   English

为什么我的cout打印两次?

[英]Why does my cout print twice?

I'm working on a text-based game and want the player to choose single or multiplayer. 我正在开发一款基于文本的游戏,希望玩家选择单人或多人游戏。 I have the following check in my code: 我在代码中进行了以下检查:

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();
}

What's happening is if the player gives an invalid input, "Please try again. Game mode: " prints twice, but if the player just hits enter it prints once. 发生的情况是,如果玩家输入的内容无效,“请重试。游戏模式:”会打印两次,但是如果玩家刚刚按下Enter,它将打印一次。 I'm a beginner to C++ and read that cin.clear() sometimes fixes this issue, but nothing has worked so far. 我是C ++的初学者,读过cin.clear()有时可以解决此问题,但到目前为止没有任何效果。

You should call cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n'); 您应该调用cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n'); after cin.clear() 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();
}

Edit: as dyp mentioned in comments sync is not guaranteed to do anything useful in this case (its behaviour is implementation defined) so the only portable way is to discard characters until new line 编辑:由于注释中提到的dyp sync在这种情况下不能保证做任何有用的事情(其行为由实现定义),因此唯一可移植的方法是丢弃字符直到换行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM