在尝试从cin获取输入时,停留在循环中 [英] Stuck in loop while trying to get input from cin

查看:112
本文介绍了在尝试从cin获取输入时,停留在循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我是C ++的新手,我经验的C#,我真的不知道我的代码是什么。我只是想弄清楚如何检查用户的输入是一个整数或字符串。

Okay I'm very new to C++, I'm experianced with C# and I don't really know what is wrong in my code. I'm just trying to figure out how to check whether the user's input is a integer or string.

但是当我键入'a'或一些其他字符串,循环永不结束。

But when I type 'a' or some other string, the while loop never ends.

    #include <iostream>

using namespace std;

int main ()
{
    int number;
    goto skip;
    do
    {
        cout << "Wrong input. Try again.";
skip:
        cout << "Number: ";
        cin >> number;
    }
    while (!cin);
    cout << "Correct input.";
    system("PAUSE");
}


推荐答案

失败模式,它将保持在失败模式,直到 clear()它的状态位。然而,仅仅清除位将不会有帮助,因为违规的字符将留在流中。重试之前最可能忽略整行:

Once your stream has gone into failure mode it will stay in failure mode until you clear() its state bits. However, merely clearing the bits won't help because the offending character will stay in the stream. Most likely you want to ignore the entire line before retrying:

while (!(std::cout << "Number: " && std::cin >> number)) {
    std::cout << "Wrong input. Try again.\n";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "Correct input.\n";
std::cin.ignore();

这篇关于在尝试从cin获取输入时,停留在循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆