cin无限循环读取非数值 [英] cin infinite loop when reading in a non-numeric value

查看:205
本文介绍了cin无限循环读取非数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个程序中有一个奇怪的行为,我花了很长时间试图推断为什么。它是一个没有意义的无限循环。测试这些代码行(怀疑)我得到了相同的结果。每次我键入一个非数字值这样的符号,程序运行通过无限循环打印零,我想是如何cout表示输入错误的值。我想知道为什么从cin的奇怪的行为,打印所有的零,而不是停止,当它发现一个错误的阅读。

I had a strange behavior in a program and I spent long time trying to deduce why. it was an infinite loop with no sense. Testing these lines of code(under suspicion) i got the same result. Every time I type in a non-numeric value such a symbol, the program runs through an infinite loop printing zeros, which i guess is how cout represents the wrong value entered. I'd like to know why is that weird behavior from cin, printing all those zeros instead of stopping when it finds a wrong reading.

#include <iostream>

using namespace std;

int main()
{
    int n = 0;
    while(n >= 0) {
        cin >> n;
        cout << n << endl;
        }
    return 0;
}


推荐答案


程序运行通过无限循环打印零,我想是 cout 如何表示输入的错误值。

the program runs through an infinite loop printing zeros, which i guess is how cout represents the wrong value entered.

这不太对:当你为 int cin 没有 int ,您没有返回任何值,但是无效输入保留在缓冲区中。当你在循环的下一次迭代中再次询问 int 时,同样的事情再次发生,并且没有进展:坏的数据保留在缓冲区中。

That is not quite right: when you ask cin for an int, but there's no int, you get no value back, but the invalid input remains in the buffer. When you ask for int again in the next iteration of the loop, same thing happens again, and no progress is made: bad data remains in the buffer.

这就是为什么你得到一个无限循环。要解决这个问题,您需要添加一些代码以从输入缓冲区中删除不良数据。例如,您可以将其读入一个字符串,并忽略输入:

That's why you get an infinite loop. To fix this, you need to add some code to remove bad data from the input buffer. For example, you could read it into a string, and ignore the input:

int n = 0;
while(n <= 0) {
    cin >> n;
    if (!cin.good()) {
        cin.clear();
        string ignore;
        cin >> ignore;
        continue;
    }
    cout << n << endl;
}

演示

这篇关于cin无限循环读取非数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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