首页 > 解决方案 > 消息并不总是出现在输入错误中

问题描述

为什么“错误:必须引入 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

谢谢。

标签: c++stringinput

解决方案


你输入的第一行被吃掉了getline(cin,instruction),所以cin.ignore(numeric_limits<streamsize>::max(),'\n');等你输入第二行然后吃掉它。只需删除cin.clear()andcin.ignore(numeric_limits<streamsize>::max(),'\n');因为getline调用已经消耗了错误的输入。


推荐阅读