【问题标题】:My cin is being ignored inside a while loop我的 cin 在 while 循环中被忽略
【发布时间】:2013-08-04 21:19:25
【问题描述】:

我正在尝试在我的第一个 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;
    }

}

【问题讨论】:

  • lives的类型是什么?
  • 我已尝试将其转换为字符串,但问题仍然存在。
  • 生命类型可能是整数或其他东西。使用 cin.get() 而不是 cin,因为您的返回值(按回车键)保留在标准输入中...
  • 好吧,使用 cin.get 它不会无限重复。但是,它在循环中给了我大约 5 或 6 次错误消息,并且在停止时甚至拒绝接受正常数字。
  • 为什么不使用命名空间标准?

标签: c++ while-loop infinite-loop cin


【解决方案1】:

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

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

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

【讨论】:

  • 饮食,它有同样的问题是在while循环之前添加两行。在您的示例中“价值”蜜蜂是什么。活着……?
  • value 是您想要阅读的任何内容,例如 int。顺便说一句,如果livesint,您对isdigit() 的测试将不起作用:此函数在chars 上运行。我很确定问题与描述的一样,您可能想打印收到的内容...
  • 好的,当使用 if 语句时,它根本不会进入 while 循环。即使我输入三或树,它也只是说我的生命得到了拯救,这对我以后的生命不起作用--。
  • 您是否尝试输入three 以将其读取为int?那会失败的!尝试使用3。如果要支持输入onetwothree,则需要自己实现字符串解析。
  • 不,那不是我正在做的。
【解决方案2】:
#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 之间,那么显然它是一个数字。

【讨论】:

  • Borg,据说 max() 需要一个标识符并且不会编译
  • @LoganSaso 我不知道你在用什么,但这在 Mingw/QtCreator 中为我编译,在 ideone 和 VS2012 上编译。
  • 我用的是Visual Studio 2012,很挑剔的东西。
  • 可能会为minmax 引入#define。尝试在包含限制之前和之后添加 #undef max,然后包含特定于 Windows 的标题。
  • 使用命名空间标准;我有 iostream 和限制
猜你喜欢
  • 2016-12-24
  • 1970-01-01
  • 2017-04-29
  • 2013-02-01
  • 2023-02-15
  • 2017-06-21
  • 2016-09-08
  • 1970-01-01
相关资源
最近更新 更多