繁体   English   中英

我的cin在while循环中被忽略了

[英]My cin is being ignored inside a while loop

我正在尝试将一个简单的问题和数字检查器编码到我的第一个C ++程序中。 问题是,当我输入一个像两个或三个字符串的字符串时,程序变为无限循环,它忽略了cin函数,将生命重新分配给一个数字。

cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
cin >> lives;


while(lives != 1 && lives != 2 && lives != 3 && !isdigit(lives))
{
    cout << "You need to input a number, not words." << endl;
    cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
    cin >> lives;
}

以下是我当前的代码以及您的建议:

    cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
std::cin.ignore();
std::cin.clear();
if (std::cin >> lives)
{


    while(lives != 1 && lives != 2 && lives != 3)
    {
        cout << "You need to input a number, not words." << endl;
        cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
        cin >> lives;
    }

}
#include <iostream>
#include <limits>

int main()
{
    int lives = 0;
    std::cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << std::endl;


    while(!(std::cin >> lives) || lives < 1 || lives > 3)
    {
        std::cout << "You need to input a number, not words." << std::endl;
        std::cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << std::endl;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

    return 0;
}

好的。 std::cin.clear(); 负责重置失败位。 std::cin.ignore删除流中剩余的任何错误输入。 而且我已经调整了停止条件。 isDigit是一个冗余的检查,如果生命在1到3之间,那么显然它是一个数字)。

std::istream无法读取值时,它将进入失败模式,即设置std::failbit并且测试时流将产生false 您始终要测试读取操作是否成功:

if (std::cin >> value) {
    ...
}

要将流恢复到良好状态,你可以使用std::cin.clear() ,你可能需要忽略坏字符,例如,使用std::cin.ignore()

暂无
暂无

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

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