c++ - 消息并不总是出现在输入错误中
问题描述
为什么“错误:必须引入 1 或 0”消息仅出现 2 次而不总是出现?
int instruction() {
string instruction;
cout << "Do you want to see the tutorial of the game? If yes press: 1, else press: 0" << endl << "--> ";
while (getline(cin,instruction)){
if (instruction == "1" || instruction == "0") {
break;
}else{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Error: Must introduce 1 or 0" << endl << "--> ";
}
}
调试输出:
Do you want to see the tutorial of the game? If yes press: 1, else press: 0
--> asdasd
asdasdasd
Error: Must introduce 1 or 0
--> sdfasdfasdf
asdf
Error: Must introduce 1 or 0
--> sad
fasd
Error: Must introduce 1 or 0
--> fas
df
Error: Must introduce 1 or 0
--> asd
fas
谢谢。
解决方案
你输入的第一行被吃掉了getline(cin,instruction)
,所以cin.ignore(numeric_limits<streamsize>::max(),'\n');
等你输入第二行然后吃掉它。只需删除cin.clear()
andcin.ignore(numeric_limits<streamsize>::max(),'\n');
因为getline
调用已经消耗了错误的输入。
推荐阅读
- javascript - 检查预定义角色并执行命令
- javascript - Javascript - 在 promise 和 await 之间不保存本地对象变量
- mysql - SQL 查询以零附加日期(月/日)值
- printers - GPRS打印机集成
- reactjs - withStyles 组件包装
- php - Laravel 5.7 - 在一定时间后杀死工匠
- mongodb - macOS Mojave 10.14.2 上缺少 libatomic
- swift - MPRemoteCommandCenter 播放/暂停 触摸时闪烁
- angular - 带有 ng-fullcalendar 包装器和角度 5 中的 fullcalendar-scheduler 扩展的 fullcalendar 标题中的“未定义”
- c# - 通用数据库检索