6

我正在尝试将一个简单的问题和数字检查器编码到我的第一个 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;
    }

}
4

2 回答 2

9
#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 之间,那么显然它是一个数字)。

于 2013-08-03T20:05:30.877 回答
3

std::istream无法读取值时,它进入故障模式,即std::failbit设置并且流false在测试时产生。您总是想测试读取操作是否成功:

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

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

于 2013-08-03T19:51:14.007 回答