为什么我的cout打印两次
Why does my cout print twice?
我正在开发一个基于文本的游戏,希望玩家选择单人或多人游戏。我的代码中有以下检查:
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
在这种情况下不能保证做任何有用的事情(它的行为是实现定义的),所以唯一的可移植方法是丢弃字符直到换行
相关文章:
- 我应该如何去缓解两次出现的cin?
- 我的字符串数组一次打印出前两个字符串
- 谷歌测试发现在macOSX上添加并运行了我的所有测试两次
- 我用C++做了一个计算器,但我对"type of calculator"的要求循环了两次。有人可以帮助指出我的错误吗?
- 为什么我需要两次相同的功能
- 为什么我的串行串行在Arduino IDE上通过串行显示器进行两次打印
- 当我叫了两次时,set_union得到了错误的结果
- C 两次之间的时间差
- 两次相同的 for 循环:一个编译,另一个不编译
- 为什么对isnan的呼吁并不含糊?a.k.a.关键字使用引入两次相似的函数声明
- 正在从文件中读取最后两次出现的内容
- 如何检查用户是否进行了两次相同的选择
- 连续运行两次后的 scons 行为
- 将两次使用的字符放在变量中是空间的增益
- 我在多映射中得到了两次相同的密钥,它只存在于文本文件中
- 两次派生的菱形继承-构造函数参数不同-指定虚拟继承时无法找到基
- 如何允许用户进行两次以上的输入
- 试着计算两次之间的差,不要相减
- 获得随机值,但不是两次相同的值
- 为什么当我删除两次相同的内存时没有错误?