c++ - 如何确保只输入 int 而不是 char?

标签 c++ function loops char int

<分区>

我写了一个函数,它只有在输入 int 时才会继续。如果 cin 失败,它将再次执行 do{...} while() 直到输入 int,而不是 字符。 我的问题是,一旦我输入一个 char,它就会陷入无限循环。我不知道为什么。

int syst ()
{
    int basisSys;
    bool opAga = false;
    do
    {
        cout << "Type the base you wanna calc. in" << endl;
        cin >> basisSys;
        if (cin.fail())
        {
            opAga = true;
        }
    }
    while (opAga == true);
    cout << endl << "You are calc. in " << basisSys << "system" << endl << endl;
    return basisSys;
}

最佳答案

重要的是忽略并清除该行,因为 operator>> 不会再从流中提取任何数据,因为它的格式错误。

while(!(cin >> basisSys)){
   cout << "Bad value!";
   cin.clear();
   cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

关于c++ - 如何确保只输入 int 而不是 char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54942935/

相关文章:

c++ - 从 C++ 中用户定义数据类型的 vector 中删除元素

javascript - JS : "this" in function context in strict mode, MDN 规范与 chrome 67 实现不匹配

javascript - 暂停 for 循环的迭代?

java - 我的循环出了什么问题?

c++ - 如何减少逻辑表达式?

c++ - 当两个父类(super class)具有同名但签名不同的成员函数时不明确

php - Azure Functions PHP 系统找不到指定的文件

javascript - 你能解释一下这个对象的属性在这些不同情况下的行为吗

c - Scanf 在循环中跳过(Hangman)

c++ - STL vector 内存管理